PostgreSQL UPDATE
Summary: in this tutorial, you will learn how to use the PostgreSQL UPDATE
statement to update existing data in a table.
Introduction to the PostgreSQL UPDATE statement
The PostgreSQL UPDATE
statement allows you to update data in one or more columns of one or more rows in a table.
Here’s the basic syntax of the UPDATE
statement:
In this syntax:
- First, specify the name of the table that you want to update data after the
UPDATE
keyword. - Second, specify columns and their new values after
SET
keyword. The columns that do not appear in theSET
clause retain their original values. - Third, determine which rows to update in the condition of the
WHERE
clause.
The WHERE
clause is optional. If you omit the WHERE
clause, the UPDATE
statement will update all rows in the table.
When the UPDATE
statement is executed successfully, it returns the following command tag:
The count
is the number of rows updated including rows whose values did not change.
Returning updated rows
The UPDATE
statement has an optional RETURNING
clause that returns the updated rows:
PostgreSQL UPDATE examples
Let’s take some examples of using the PostgreSQL UPDATE
statement.
Setting up a sample table
The following statements create a table called courses
and insert data into it:
Output:
1) Basic PostgreSQL UPDATE example
The following statement uses the UPDATE
statement to update the course with id 3 by changing the published_date
to '2020-08-01'
.
The statement returns the following message indicating that one row has been updated:
The following statement retrieves the course with id 3 to verify the update:
Output:
2) Updating a row and returning the updated row
The following statement uses the UPDATE
statement update published_date
of the course id 2 to 2020-07-01
and returns the updated course.
Output:
3) Updating a column with an expression
The following statement uses an UPDATE
statement to increase the price of all the courses 5%:
Because we don’t use a WHERE clause, the UPDATE statement updates all the rows in the courses
table.
Output:
The following statement retrieves data from the courses
table to verify the update:
Output:
Output:
Summary
- Use the
UPDATE
statement to update data in one or more columns of a table. - Specify a condition in a WHERE clause to determine which rows to update data.
- Use the
RETURNING
clause to return the updated rows from theUPDATE
statement