Explain it simply
Explain it simply
UPDATE is like erasing lines already written in a ledger and writing new values over them. SET says what to change and how, and WHERE says which lines to change. Editing a user profile, marking an order as "shipped" and correcting a product price are all UPDATEs.
The most important part is WHERE. Forget it and the database understands "every line" and changes the whole table, without asking "are you sure?".
Problem → Why → Solution
The problem: fixing one price changes every product
A shop admin types a query to fix the price of the KB-01 keyboard. The WHERE line is written, but only the first two lines are highlighted when they press run. psql answers UPDATE 4: all four products now cost 39.00. No transaction was open, so there is nothing to roll back.
UPDATE products
SET price = 39.00
-- WHERE sku = 'KB-01'; <- never executed
-- psql: UPDATE 4Why is this so dangerous?
An UPDATE without WHERE is perfectly valid SQL meaning "every row", so the database gives no warning. psql and most application drivers run in autocommit mode, so the change is permanent the moment the statement finishes. The protection is a habit: test the WHERE with a SELECT, open a transaction with BEGIN, check the number in UPDATE n, and only then COMMIT.
Core concept: WHERE picks, SET changes
PostgreSQL runs UPDATE table SET col = expression WHERE condition in two phases. First it finds rows with the WHERE, exactly like a SELECT; then, for each row found, it evaluates the SET expressions. So running a SELECT with the same WHERE is an exact preview of which rows will change. Separate several assignments with commas to change multiple columns at once.
The expressions on the right-hand side of SET see the row's values from before the update. That is why price = price * 1.10 raises the current price by 10%, and why SET a = b, b = a swaps two values in PostgreSQL. MySQL instead applies single-table assignments left to right, so the same swap does not work there; keep that in mind when porting.
An expression such as stock = stock - 1 is atomic: PostgreSQL locks the row and computes from its current value, so two simultaneous purchases correctly reduce stock by two. Reading stock with a SELECT, subtracting in JavaScript and writing stock = 9 back causes a "lost update". Adding WHERE stock > 0 leaves sold-out rows untouched and returns UPDATE 0, which tells you the item is gone.
Constraints check UPDATEs too: setting a NOT NULL column to NULL or breaking CHECK (stock >= 0) fails the whole statement, and not a single row changes. For every completed UPDATE psql prints UPDATE n, where n is the number of rows changed. Add RETURNING to get the new values back like a SELECT.
- SELECT with the same WHERE
- Open a transaction with BEGIN
- Run UPDATE ... RETURNING
- Compare UPDATE n with your guess
- COMMIT or ROLLBACK
Until COMMIT, ROLLBACK undoes the change completely.
General pattern
BEGIN;
UPDATE table_name
SET column_a = new_value,
column_b = column_b + 1
WHERE key_column = key_value
RETURNING key_column, column_a, column_b;
COMMIT; -- or ROLLBACK; if the result looks wrongSET can change several columns separated by commas, and the right-hand side may use the current value. WHERE picks the rows, RETURNING (PostgreSQL) shows the result, and BEGIN plus COMMIT or ROLLBACK lets you decide whether the change stays.
Example: change one customer's contact and city
Alfreds Futterkiste has a new contact person, Alfred Schmidt, and has moved to Frankfurt. The two queries show the "SELECT first" habit: the first confirms that the WHERE matches exactly one row, and the second changes that row and shows the new values.
CREATE TABLE customers (
customer_id integer PRIMARY KEY,
customer_name text NOT NULL,
contact_name text,
city text,
country text
);
INSERT INTO customers VALUES
(1, 'Alfreds Futterkiste', 'Maria Anders', 'Berlin', 'Germany'),
(2, 'Ana Trujillo', 'Ana Trujillo', 'Mexico City', 'Mexico'),
(3, 'Antonio Moreno', 'Antonio Moreno', 'Mexico City', 'Mexico'),
(4, 'Around the Horn', 'Thomas Hardy', 'London', 'UK');-- 1. Look first, with the same WHERE the UPDATE will use
SELECT customer_id, contact_name, city
FROM customers
WHERE customer_id = 1;
-- 2. Change exactly that row and show the new values
UPDATE customers
SET contact_name = 'Alfred Schmidt', city = 'Frankfurt'
WHERE customer_id = 1
RETURNING customer_id, contact_name, city;Code breakdown
- Preview
WHERE customer_id = 1;The exact WHERE the UPDATE will use runs first in a SELECT. One row comes back, and you also capture the current values, Maria Anders and Berlin.
- SET
SET contact_name = 'Alfred Schmidt', city = 'Frankfurt'Two columns change in one statement, separated by a comma. customer_name and country are not in SET, so they stay as they are.
- WHERE on the key
WHERE customer_id = 1Filtering on the primary key can match at most one row. WHERE customer_name = 'Alfreds Futterkiste' would change both customers on the day two of them share that name.
- RETURNING
RETURNING customer_id, contact_name, city;The updated row comes back, so you see Frankfurt without another query. The final UPDATE 1 confirms that exactly one row changed.
customer_id | contact_name | city
-------------+--------------+--------
1 | Maria Anders | Berlin
(1 row)
customer_id | contact_name | city
-------------+----------------+-----------
1 | Alfred Schmidt | Frankfurt
(1 row)
UPDATE 1Updating inside a transaction
Inside a transaction opened with BEGIN, your own session sees the UPDATE's effect, but other sessions do not until you COMMIT. If RETURNING shows something wrong, ROLLBACK puts everything back. In the snippet below, the UPDATE without WHERE touches all four rows, yet the ROLLBACK leaves every price intact.
BEGIN;
UPDATE products SET price = 0 RETURNING sku; -- UPDATE 4: oops, no WHERE
ROLLBACK; -- nothing was changed
SELECT sku, price FROM products ORDER BY product_id; -- original pricesDo not leave a transaction open
Rows changed by an UPDATE stay locked until COMMIT or ROLLBACK. Run BEGIN in production and walk off to lunch, and every app request that tries to modify those rows waits for you. Decide as soon as you have checked.
Updating from another table
When new supplier prices land in a price_changes table, PostgreSQL's UPDATE ... FROM joins the two tables and applies them. This is PostgreSQL syntax: SQL Server also has UPDATE ... FROM with slightly different rules, and MySQL writes UPDATE products JOIN price_changes ... instead.
UPDATE products AS p
SET price = c.new_price
FROM price_changes AS c
WHERE p.sku = c.sku
RETURNING p.sku, p.price; -- CB-01 9.00, KB-01 42.00In real projects
Where this shows up in real projects
In application code almost every UPDATE puts both the primary key and the owner in its WHERE: UPDATE orders SET status = 'cancelled' WHERE id = $1 AND user_id = $2 AND status = 'pending'. user_id stops one user from editing another's order, and status = 'pending' prevents cancelling an order that has already shipped. When the affected row count is 0, the backend answers 404 or 409.
For manual "data fixes" on production, many teams follow one rule: start the script with BEGIN, write the expected row count in the ticket beforehand, COMMIT only if UPDATE n matches it, and ROLLBACK otherwise. When millions of rows must change, they run small batches by id range so no lock is held for long.
Common mistakes
Common mistakes
1. Forgetting WHERE, or running only half the statement
Highlighting only some lines in a query editor and running them has the same effect as forgetting WHERE. Write the WHERE before the SET (start with the table and the condition, then fill in the assignments), run it inside BEGIN, and check UPDATE n.
2. Computing in the app and writing the value back
Read stock = 10 with SELECT, compute 9 in the app, then UPDATE ... SET stock = 9: two simultaneous buyers both write 9 and one sale vanishes. Let the database compute it: SET stock = stock - 1 WHERE ... AND stock > 0.
3. Selecting the row by a non-unique column
WHERE customer_name = 'Ana Trujillo' matches one row today, but the day a second customer with that name signs up, both change. When you mean one row, select it by the primary key or another unique column.
Best practices
Best practices
- When changing one row, select it by primary key, and in application code add the owner column to the WHERE as well.
- Start every manual data fix with BEGIN and compare the row count with the number you predicted.
- Put calculations inside SET instead of reading, computing and writing back from the app.
- Have the app always check the affected row count and treat 0 as an error case.
Mini challenge
Mini challenge: raise prices and sell one unit
In one transaction, write two UPDATEs: raise every cable's price by 10% (rounded to 2 decimals), then sell one MN-27 monitor, reducing stock only if there is any left.
- Start with BEGIN and finish with COMMIT
- The first UPDATE changes only the two cables and returns sku and price
- The second UPDATE uses stock = stock - 1 and checks stock > 0 in WHERE
- Selling the keyboard (stock 0) the same way must give UPDATE 0
CREATE TABLE products (
product_id integer PRIMARY KEY,
sku text NOT NULL UNIQUE,
category text NOT NULL,
price numeric(8, 2) NOT NULL,
stock integer NOT NULL CHECK (stock >= 0)
);
INSERT INTO products VALUES
(1, 'CB-01', 'cable', 8.50, 100),
(2, 'CB-02', 'cable', 12.00, 40),
(3, 'MN-27', 'monitor', 249.00, 1),
(4, 'KB-01', 'keyboard', 45.00, 0);
BEGIN;
-- TODO: +10% for category 'cable', rounded to 2 decimals; return sku, price
-- TODO: sell one 'MN-27' only if stock > 0; return sku, stock
COMMIT;Expected: First UPDATE: CB-01 9.35 and CB-02 13.20 (UPDATE 2). Second UPDATE: MN-27 with stock 0 (UPDATE 1). Trying KB-01 returns no row and UPDATE 0.
Show hint
round(price * 1.10, 2) gives two decimal places. When stock is 0, WHERE ... AND stock > 0 selects no row, so you get UPDATE 0 instead of a CHECK constraint error.
Show solution
BEGIN;
UPDATE products
SET price = round(price * 1.10, 2)
WHERE category = 'cable'
RETURNING sku, price;
UPDATE products
SET stock = stock - 1
WHERE sku = 'MN-27' AND stock > 0
RETURNING sku, stock;
COMMIT;Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- UPDATE ... SET ... WHERE: WHERE picks rows, SET changes values; no WHERE means every row.
- Preview with a SELECT that uses the same WHERE.
- Change data inside BEGIN, check RETURNING and UPDATE n, then COMMIT, or ROLLBACK if it is wrong.
- The right-hand side of SET sees old values, which makes atomic updates like stock = stock - 1 possible.
PostgreSQL SQL Tutorial — PostgreSQL Global Development Group