Updating Rows With UPDATE: Expressions, Subqueries and Joins
How to change existing rows with UPDATE: SET and WHERE, expressions that use the old values, CASE for different changes per row, correlated subqueries and the NULL trap, UPDATE with joins in each database, constraints, NULL handling and how to update safely.
kvi5hnuCode Sprout team member11 min readOn this page
UPDATE changes values in rows that already exist: a new price, a corrected address, an order that has shipped. Its syntax is short, but it's the statement most likely to cause a bad day, because a missing or wrong WHERE clause changes rows you didn't mean to touch, and there's no "undo" once the change is committed.
This article covers the statement itself, how it computes new values, updating from other tables with subqueries and joins, and the habits that keep updates safe. The examples run on the shop database, starting from a fresh copy each time.
The basic UPDATE
UPDATE table
SET column1 = expression1,
column2 = expression2
WHERE condition;
SETlists the columns to change and their new values, separated by commas. Columns not mentioned keep their values.WHEREchooses which rows to change, exactly as in aSELECT. Rows for which the condition is false or unknown aren't changed.- Without
WHERE, every row in the table is changed.
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Raise the price of every pack by 10% and record a new stock level
UPDATE products
SET price = ROUND(price * 1.10, 2),
stock = stock + 5
WHERE category = 'packs';
SELECT product_id, name, category, price, stock
FROM products
ORDER BY product_id;
product_id | name | category | price | stock
------------+-------------------+----------+--------+-------
1 | Ridge 2 tent | tents | 249.99 | 12
2 | Summit 4 tent | tents | 489.00 | 3
3 | Glow head torch | lighting | 34.50 | 40
4 | Basecamp lantern | lighting | 27.00 | 15
5 | Trail 30 backpack | packs | 98.95 | 27
6 | Day 18 backpack | packs | 59.40 | 5
7 | Merino socks | clothing | 16.00 | 75
(7 rows)
The expressions in SET can use the row's current values: price * 1.10 raises each pack's price by 10%, and stock + 5 adds to the current stock. Only the two packs changed. The other five rows are untouched.

Expressions, CASE and old values
Because SET takes expressions, a CASE expression can apply different changes to different rows in one statement:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Different changes for different rows with CASE
UPDATE products
SET price = CASE category
WHEN 'tents' THEN price * 0.90 -- 10% off tents
WHEN 'clothing' THEN price + 1.00 -- socks up by 1.00
ELSE price -- everything else unchanged
END
WHERE category IN ('tents', 'clothing');
SELECT name, category, price FROM products ORDER BY product_id;
-- Every expression in SET sees the row's OLD values, so this swaps two columns
CREATE TABLE pairs (id INTEGER PRIMARY KEY, a INTEGER, b INTEGER);
INSERT INTO pairs VALUES (1, 10, 20);
UPDATE pairs SET a = b, b = a;
SELECT * FROM pairs;
name | category | price
-------------------+----------+--------
Ridge 2 tent | tents | 224.99
Summit 4 tent | tents | 440.10
Glow head torch | lighting | 34.50
Basecamp lantern | lighting | 27.00
Trail 30 backpack | packs | 89.95
Day 18 backpack | packs | 54.00
Merino socks | clothing | 17.00
(7 rows)
id | a | b
----+----+----
1 | 20 | 10
(1 row)
The tents get 10% off and the socks go up by 1.00, in a single pass over the table. The ELSE price is important: without it, CASE returns NULL for any row that matches no WHEN. Here the WHERE already restricts the update to tents and clothing, but keeping ELSE price protects you if the WHERE changes later.
The Summit tent's new price is 440.10, and the Ridge tent's is 224.99: 249.99 × 0.90 is 224.991, which is rounded to fit DECIMAL(8, 2).
The second part shows a rule of standard SQL: every expression in SET reads the row's values from before the update. SET a = b, b = a computes both new values from the old row, so it swaps the columns. PostgreSQL, SQL Server, Oracle and SQLite follow this rule.
MySQL doesn't. It performs single-table assignments from left to right, and later assignments see the new values. In MySQL, SET a = b, b = a sets a to 20 and then b to the new a, which is also 20. To swap columns in MySQL, use a temporary value or a self-join.
Updating from a subquery
A new value often comes from another table. A correlated subquery in SET computes a value for each row being updated. Here, the shop wants to reduce each product's stock by the quantity on pending orders:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Reserve stock for pending orders. First attempt: a correlated subquery in SET...
UPDATE products
SET stock = stock - (SELECT SUM(oi.qty)
FROM order_items oi
JOIN orders o ON o.order_id = oi.order_id
WHERE o.status = 'pending'
AND oi.product_id = products.product_id);
-- ...fails: products with no pending order get stock - NULL = NULL.
-- Restrict the update to the products the subquery has a value for:
UPDATE products
SET stock = stock - (SELECT SUM(oi.qty)
FROM order_items oi
JOIN orders o ON o.order_id = oi.order_id
WHERE o.status = 'pending'
AND oi.product_id = products.product_id)
WHERE product_id IN (SELECT oi.product_id
FROM order_items oi
JOIN orders o ON o.order_id = oi.order_id
WHERE o.status = 'pending');
SELECT product_id, name, stock FROM products ORDER BY product_id;
psql:/workspace/solution.sql:68: ERROR: null value in column "stock" of relation "products" violates not-null constraint
DETAIL: Failing row contains (1, Ridge 2 tent, tents, Alpina, 249.99, null, 2100).
product_id | name | stock
------------+-------------------+-------
1 | Ridge 2 tent | 12
2 | Summit 4 tent | 2
3 | Glow head torch | 40
4 | Basecamp lantern | 15
5 | Trail 30 backpack | 22
6 | Day 18 backpack | 0
7 | Merino socks | 75
(7 rows)
The first attempt fails, and the reason is a classic mistake. It has no WHERE, so it updates every product. For products with no pending order, the subquery finds no rows and SUM returns NULL. stock - NULL is NULL, and NULL violates the NOT NULL constraint on stock. If the column allowed NULLs, the statement would succeed and silently wipe the stock of six products.
The second version adds a WHERE that limits the update to products that appear on a pending order, so the subquery always finds a value. Only the Summit tent changed, from 3 to 2. Another fix is COALESCE((SELECT SUM(...) ...), 0), which subtracts 0 from products with no pending orders but still rewrites every row.
Rule: when SET uses a subquery, make sure the WHERE clause matches only the rows for which the subquery returns a value.
In MySQL, a subquery in an UPDATE can't read from the table being updated: UPDATE products SET ... WHERE price > (SELECT AVG(price) FROM products) fails with "You can't specify target table 'products' for update in FROM clause". Wrapping the subquery in a derived table, (SELECT avg_price FROM (SELECT AVG(price) AS avg_price FROM products) AS t), works around it, because MySQL materializes the derived table first.
Updating with a join
The subquery approach repeats itself when the same tables are needed in both SET and WHERE. Most databases let UPDATE join to other tables directly, but the syntax isn't standard, and each database has its own. PostgreSQL uses UPDATE ... FROM:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
\pset null '(null)'
-- UPDATE ... FROM: set each pending order line to 95% of the product's current price
UPDATE order_items oi
SET unit_price = p.price * 0.95
FROM products p, orders o
WHERE p.product_id = oi.product_id
AND o.order_id = oi.order_id
AND o.status = 'pending';
SELECT order_id, product_id, unit_price FROM order_items WHERE order_id = 104;
-- Change orders using a value from another table: Pune customers' open orders
UPDATE orders o
SET status = 'priority'
FROM customers c
WHERE c.customer_id = o.customer_id
AND c.city = 'Pune'
AND o.status IN ('pending', 'shipped');
SELECT o.order_id, c.name, c.city, o.status
FROM orders o
LEFT JOIN customers c ON c.customer_id = o.customer_id
ORDER BY o.order_id;
order_id | product_id | unit_price
----------+------------+------------
104 | 2 | 464.55
(1 row)
order_id | name | city | status
----------+------------+--------+-----------
101 | Asha Rao | Pune | priority
102 | Ben Okafor | Leeds | shipped
103 | Asha Rao | Pune | delivered
104 | Chen Wei | Pune | priority
105 | Dana Cruz | York | cancelled
106 | (null) | (null) | shipped
(6 rows)
- The tables in
FROMare joined to the target table by the conditions inWHERE. Each target row that finds a match is updated, and theSETexpressions can use the joined tables' columns:p.price * 0.95. - In PostgreSQL, don't repeat the target table in
FROM. That would create a second, unrelated copy of it, joined to every row. - The first statement updates the pending order's line to 95% of the current price, 464.55. The second sets the status of open orders from Pune customers to
'priority'. The guest order has no customer, so the join finds no match and it's left alone.
The same join in other databases:
-- MySQL and MariaDB: join in the UPDATE clause
UPDATE orders o
JOIN customers c ON c.customer_id = o.customer_id
SET o.status = 'priority'
WHERE c.city = 'Pune' AND o.status IN ('pending', 'shipped');
-- SQL Server: UPDATE alias ... FROM with a join
UPDATE o
SET o.status = 'priority'
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
WHERE c.city = 'Pune' AND o.status IN ('pending', 'shipped');
-- Oracle and portable: a subquery in WHERE
UPDATE orders
SET status = 'priority'
WHERE status IN ('pending', 'shipped')
AND customer_id IN (SELECT customer_id FROM customers WHERE city = 'Pune');
SQLite supports PostgreSQL's UPDATE ... FROM since version 3.33. Oracle 23ai added a FROM clause to UPDATE too. Before that, Oracle used subqueries or MERGE, which article 34 covers and which works in most databases.
Watch out for multiple matches. If a target row joins to two or more rows in FROM, it's updated only once, with values from one of the matching rows, chosen arbitrarily. PostgreSQL and SQL Server give no error. Make sure the join finds at most one row per target row, for example by joining on a key or aggregating first. MERGE raises an error in this situation instead, which is one reason to prefer it.
NULL, constraints and errors
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
\pset null '(null)'
-- = NULL is never true, so this changes nothing
UPDATE products SET brand = 'Unbranded' WHERE brand = NULL;
SELECT COUNT(*) AS unbranded FROM products WHERE brand = 'Unbranded';
-- IS NULL finds the lantern
UPDATE products SET brand = 'Unbranded' WHERE brand IS NULL;
SELECT name, brand FROM products WHERE product_id = 4;
-- Setting a column TO null uses =, as in any assignment
UPDATE products SET weight_g = NULL WHERE product_id = 7;
-- Constraints apply to updates too; the whole statement is rejected
ALTER TABLE products ADD CONSTRAINT stock_not_negative CHECK (stock >= 0);
UPDATE products SET stock = stock - 10; -- would make two rows negative
SELECT name, stock FROM products ORDER BY stock FETCH FIRST 3 ROWS ONLY;
unbranded
-----------
0
(1 row)
name | brand
------------------+-----------
Basecamp lantern | Unbranded
(1 row)
psql:/workspace/solution.sql:77: ERROR: new row for relation "products" violates check constraint "stock_not_negative"
DETAIL: Failing row contains (2, Summit 4 tent, tents, Alpina, 489.00, -7, 4300).
name | stock
-----------------+-------
Day 18 backpack | 0
Summit 4 tent | 3
Ridge 2 tent | 12
(3 rows)
WHERE brand = NULLis never true (article 8), so the first update changes nothing, and no error warns you.WHERE brand IS NULLfinds the lantern.- In
SET,= NULLis an assignment, not a comparison, soSET weight_g = NULLworks as expected. - Constraints apply to updates as to inserts. Subtracting 10 from every stock level would make two products negative, which breaks the new
CHECKconstraint. The whole statement is rejected, so the products that would have stayed positive weren't changed either: Ridge 2 tent still has 12.
Changing a primary key value with UPDATE is allowed, but rows in other tables that reference it would then point to a missing row. By default, the foreign key blocks the change. Article 53 covers ON UPDATE CASCADE and the other actions. In general, design keys that never need to change.
Updating safely
A wrong UPDATE can be one of the hardest mistakes to recover from. These habits prevent most accidents:
- Write the
WHEREclause first and test it with aSELECT:SELECT * FROM products WHERE category = 'packs'. When it returns exactly the rows you expect, turn it into theUPDATE. - Check the row count the database reports, such as
UPDATE 2. If you expected 2 rows and it says 7,000, something is wrong. - Use a transaction for anything important:
BEGIN, run the update, check the result, thenCOMMIT, orROLLBACKto undo it (article 60). - Use
RETURNINGin PostgreSQL and SQLite, orOUTPUTin SQL Server, to see the changed rows (article 34). - Update by key when changing single rows:
WHERE product_id = 6can never match more than one row. - In MySQL, the
sql_safe_updatessetting (enabled by default in MySQL Workbench) rejects anUPDATEorDELETEwithout a key-basedWHEREorLIMIT.
Performance
An UPDATE must find the rows to change, so an index on the WHERE columns helps it just as it helps a SELECT. Updating many rows is expensive, though: every changed row is written, every index on a changed column is updated, and the change is logged. In PostgreSQL, an update writes a new version of the row (article 61 explains why), so updating a whole large table roughly doubles its size. VACUUM makes the dead space reusable, but the file stays large unless it's rewritten, for example with VACUUM FULL.
For very large updates, split the work into batches, for example by key range, so that each transaction stays short and other sessions aren't blocked for long. Avoid updating rows that wouldn't change: WHERE status <> 'priority' skips rows that already have the value.
What's current
- Oracle 23ai added direct joins in
UPDATEandDELETE(UPDATE ... FROM), bringing Oracle closer to PostgreSQL's syntax. - SQLite 3.33 added
UPDATE ... FROM, and SQLite 3.35 addedRETURNING. - MySQL 9 still evaluates single-table
SETassignments left to right, unlike the SQL standard.
Common questions
What happens if I forget the WHERE clause?
Every row in the table is updated. If you're inside a transaction, ROLLBACK undoes it. Otherwise, restore the data from a backup.
Can SET use the column's old value?
Yes. SET price = price * 1.10 reads the current price. In standard SQL, every SET expression sees the values from before the update.
Why did my update set some values to NULL?
Usually a correlated subquery in SET found no row for some target rows, or a CASE without ELSE matched none of its conditions.
How do I update a table using values from another table?
With a correlated subquery in SET, with the join syntax of your database (UPDATE ... FROM or UPDATE ... JOIN), or with MERGE.
Can I update several tables in one statement?
MySQL's multi-table UPDATE can. In standard SQL and most databases, one UPDATE changes one table. Use a transaction to change several tables together.
Does UPDATE lock the rows?
Yes. Updated rows are locked until the transaction ends, so other transactions that try to update the same rows wait. Article 61 covers locking.
Summary
UPDATE table SET column = expression WHERE conditionchanges the matching rows. WithoutWHERE, it changes every row.SETexpressions can use the row's current values. In standard SQL, they all see the old values. MySQL evaluates them left to right.CASEinSETapplies different changes to different rows. IncludeELSE columnto keep the other rows unchanged.- A correlated subquery in
SETreturns NULL for rows with no match. Restrict theWHEREto rows with a match, or useCOALESCE. - Join syntax differs:
UPDATE ... FROMin PostgreSQL, SQLite and SQL Server,UPDATE ... JOINin MySQL, subqueries orMERGEin Oracle before 23ai. Make sure each target row matches at most one source row. - Constraints are checked, and the statement is all or nothing. Test the
WHEREwith aSELECT, check the row count, and use transactions.
Practice questions
Write an UPDATE that sets the stock of every product with 0 in stock to 10.
Answer
UPDATE products
SET stock = 10
WHERE stock = 0;
Only the Day 18 backpack changes.
What does UPDATE products SET price = price * 2, stock = price store in stock for the socks (price 16.00), in PostgreSQL?
Answer
16, the old price, because every SET expression reads the values from before the update. The new price is 32.00. In MySQL, stock would get 32, the price that was just assigned.
Rewrite this update so that it doesn't set city to NULL for customers with no matching row in new_addresses(customer_id, city):
UPDATE customers
SET city = (SELECT n.city FROM new_addresses n
WHERE n.customer_id = customers.customer_id);
Answer
UPDATE customers
SET city = (SELECT n.city FROM new_addresses n
WHERE n.customer_id = customers.customer_id)
WHERE EXISTS (SELECT 1 FROM new_addresses n
WHERE n.customer_id = customers.customer_id);
In PostgreSQL, the join form is shorter: UPDATE customers c SET city = n.city FROM new_addresses n WHERE n.customer_id = c.customer_id.
An UPDATE ... FROM joins products to a price_list table that contains two rows for product 3, with different prices. What price does product 3 get?
Answer
One of the two, chosen arbitrarily. PostgreSQL and SQL Server don't raise an error. Fix the data or the join so that each product matches one row, or use MERGE, which raises an error when a target row matches several source rows.
Before running UPDATE orders SET status = 'cancelled' WHERE placed_on < DATE '2026-03-10' AND status = 'pending', what should you run to check it?
Answer
The same WHERE in a SELECT: SELECT * FROM orders WHERE placed_on < DATE '2026-03-10' AND status = 'pending'. If it returns the expected rows (here none, since the only pending order is from 15 March), run the update, ideally in a transaction, and compare the reported row count with the SELECT.
Previous: Inserting Rows With INSERT: Values, Defaults and INSERT ... SELECT
Next: Deleting Rows: DELETE, TRUNCATE and Removing Duplicates

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.