PostgreSQL

PostgreSQL UPDATE

Modify existing rows in a PostgreSQL table with the UPDATE statement.

Before you begin: Make sure the products table has name and color columns, then check the rows with SELECT before updating them.

Update a row

Use UPDATE with SET to assign a new value and WHERE to identify the row to change. For example, set the color of the Laptop to red:

UPDATE products
SET color = 'red'
WHERE name = 'Laptop';

The WHERE name = 'Laptop' condition limits the update to rows whose name is Laptop. Text values use single quotation marks, while numeric values do not.

Result

PostgreSQL reports:

UPDATE 1

This means that one row was affected by the UPDATE statement. If multiple products match the condition, the number will be larger.

Display the table

To check the updated value, display the table with this statement:

SELECT * FROM products;

Warning: remember WHERE

Be careful when updating records. If you omit the WHERE clause, PostgreSQL updates every row in the table.

UPDATE products
SET color = 'red';

If the table contains four rows, PostgreSQL reports:

UPDATE 4

All four rows were updated, not just the Laptop row.

Further Reading

Continue learning with these related tutorials:

Continue learning