← Back to PostgreSQL Course | Chapter 4: Inserting & Modifying Data | Lesson 3 of 7

UPDATE

UPDATE changes existing rows that match a WHERE condition.

In this page:

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

UPDATE

UPDATE table SET col = value [, ...] WHERE condition. Without WHERE every row is changed, so always check the condition first, ideally with a SELECT.

Values can be expressions using other columns, such as price = price * 1.1.

Wrap risky updates in a transaction.

Note: Run the WHERE clause as a SELECT before running the UPDATE.

Example: UPDATE

sql
CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, price INTEGER, category TEXT);
INSERT INTO products VALUES (1, 'Pen', 3, 'office'), (2, 'Desk', 150, 'furniture'), (3, 'Notebook', 8, 'office');
UPDATE products SET price = price + 2 WHERE category = 'office';
SELECT name, price FROM products ORDER BY id;
UPDATE products SET category = 'stationery' WHERE name = 'Pen';
SELECT name, category FROM products ORDER BY id;

-- Output:
-- name | price
-- Pen | 5
-- Desk | 150
-- Notebook | 10
-- name | category
-- Pen | stationery
-- Desk | furniture
-- Notebook | office
Related Topics
Common Mistakes
  1. Forgetting the WHERE clause
  2. Updating with an ambiguous condition
  3. Not using a transaction for risky changes
Chapter Summary
  • UPDATE SET changes columns
  • WHERE picks the rows
  • Without WHERE all rows change
  • Values can be expressions
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.