How to use the UPDATE Command in PostgreSQL

👋 Hey there! Today, we’re diving into one of the fundamental commands in PostgreSQL: the UPDATE command. This command lets you modify existing records in a table, and understanding its nuances can make your life a whole lot easier.

What Does UPDATE Do?

The UPDATE command changes existing records in a table. Whether you need to correct a typo in a single field or update information for multiple rows, this command has got you covered.

Basic Syntax

Here’s the basic syntax for the UPDATE command:

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

The WHERE clause specifies which record(s) should be updated. If you omit the WHERE clause, all records in the table will be updated!

Update a Single Row

Let’s say you have a tv_series table and you realize that the name of a particular TV series is incorrect. Here’s how you’d correct it:

UPDATE tv_series
SET name = 'Corrected Name'
WHERE id = 1;

This changes the name of the series with id 1 to "Corrected Name."

Update Multiple Rows

Imagine the release_year for all series released in 2018 should actually be 2019. You can update multiple rows like this:

UPDATE tv_series
SET release_year = 2019
WHERE release_year = 2018;

Update Multiple Columns

Need to correct more than one column? No worries. Here’s how:

UPDATE tv_series
SET name = 'New Name', release_year = 2020
WHERE id = 1;

This updates both the name and release_year for the series with id 1.

Using Expressions and Functions

You’re not limited to static values. PostgreSQL allows for expressions and built-in functions:

UPDATE tv_series
SET episodes = episodes + 1
WHERE id = 1;

This increases the episodes count by 1 for the series with id 1.

Common Errors and Solutions

Error Message:

ERROR:  column "column_name" of relation "table_name" does not exist


The column you’re trying to update doesn’t exist in the table.


Check your table’s structure to ensure you’ve got the right column name.

Error Message:

ERROR:  null value in column "column_name" violates not-null constraint


You’re trying to set a NOT NULL column to NULL.


Make sure you’re not setting a NOT NULL column to NULL, or alter the table to allow NULL values.

Wrap Up

The UPDATE command in PostgreSQL is like a Swiss army knife for modifying your data. Once you get the hang of it, you’ll find it incredibly handy for day-to-day database tasks. So go ahead, try these examples on your tv_series table and get updating!

Happy querying! 🎉

Leave a Reply