skip to content

UPDATE and DELETE

the WHERE you forgot, UPDATE ... FROM, DELETE ... USING, and TRUNCATE.

address
everything.writes.update_and_delete
part
part 5, changing data
chapter
chapter 2 of 10
reading time
9 min

UPDATE changes columns in the rows its WHERE matches, and DELETE removes the rows its WHERE matches. no WHERE matches every row. the command tag (UPDATE 2000) tells you how many, so BEGIN first and read it before you COMMIT.

UPDATE ... FROM and DELETE ... USING bring in other tables. TRUNCATE empties a table without touching its rows at all.

the picture

you know find and replace in a text editor? the search box picks what changes, the replace box says what it becomes, and an empty search box means everything. UPDATE is that, for rows: WHERE is the search box, SET is the replace box.

the difference is that an editor shows you the matches first. UPDATE just does it, and then tells you how many it did.

before anything runs
customers, 7 of them, after this stepthe whole table: 2,000 rows
customers, 7 of them after: before
idint4nametextcitytext
1Maya ChenSan Francisco
2Grace OkaforLagos
3Sam LeeToronto
4Zoë MartinParis
5Zoe MartinLyon
6José Silvanull
42Ada LovelaceLondon
(7 rows)
changed

seven customers, a window into a table of 2,000.

step 1/5
real output, postgres 18.6 (PGlite 0.5.12) · update-delete
step through. with a WHERE, one customer of 2,000 moves to Paris. without it, all of them do: every row in the window turns hot and the tag says UPDATE 2000. both run inside BEGIN, so ROLLBACK puts everything back.

notice Zoë. she already lived in Paris, so her cell doesn't change colour, but she's in the 2,000 anyway. UPDATE counts the rows it wrote, not the rows whose values changed. (and it really does write each of them: in postgres every updated row is a brand new row version, even when nothing in it is different.)

nothing on this page sticks, by the way: every block starts from a fresh copy of the shop database. break whatever you like.

UPDATE

name the table, SET the columns, and WHERE picks the rows. here every book gets 10% dearer:

sqldb=shop
UPDATE products SET price = round(price * 1.10, 2) WHERE category = 'books';
SELECT id, name, price FROM products WHERE category = 'books' ORDER BY id LIMIT 4;
output, from postgres 18.6
#1 · UPDATE 12
#2 · SELECT 4
idint4nametextpricenumeric
3the art of sql35.20
28bamboo cookbook18.59
53mini notebook168.96
54compact novel81.14
(4 rows)

UPDATE 12: there are 12 books. the right-hand side of SET can use the row's own columns, and every one of them means the value before this update. so assignments don't see each other, and this really does swap two columns:

sqldb=shop
UPDATE products SET name = sku, sku = name WHERE id = 3;
SELECT id, sku, name FROM products WHERE id = 3;
output, from postgres 18.6
#1 · UPDATE 1
#2 · SELECT 1
idint4skutextnametext
3the art of sqlBOO-0003
(1 row)
predict the output
sql
UPDATE products SET category = 'misc' WHERE category = NULL;
sqldb=shop
UPDATE products SET category = 'misc' WHERE category = NULL;
UPDATE products SET category = 'misc' WHERE category IS NULL;
output, from postgres 18.6
#1 · UPDATE 0
#2 · UPDATE 3

BEGIN first

the habit that saves you is boring: open a transaction, run the change, read the tag, and only then decide.

sqldb=shop
BEGIN;
UPDATE customers SET city = 'Paris';
ROLLBACK;
output, from postgres 18.6
#1 · BEGIN
#2 · UPDATE 2000
#3 · ROLLBACK

UPDATE 2000, when you expected UPDATE 1. inside BEGIN that's a shrug and a ROLLBACK. in autocommit (every statement its own transaction, which is the default in psql and in most drivers) it's already committed by the time you read it, and the way back is a backup. BEGIN, COMMIT and ROLLBACK has the details, including what a transaction left open does to everyone else.

two more habits: write the WHERE first and the SET second (an UPDATE with half a WHERE is still a whole UPDATE), and run the same WHERE as a SELECT count(*) before you trust it.

UPDATE ... FROM

sometimes the new value lives in another table: a price feed, a staging table, a list somebody sent you. FROM joins it in, and the WHERE says how the rows pair up. the feed here is a VALUES list, but it could be any table or query.

statement =
feed =
feed.sql
  1. 1UPDATE products AS p
  2. 2SET price = f.price
  3. 3FROM (VALUES ('BOO-0003', 29.00), ('BOO-0028', 15.50)) AS f (sku, price)
  4. 4WHERE p.sku = f.sku
  5. 5RETURNING p.sku, p.name, p.price;
the result for UPDATE ... FROM | one row per sku
skutextnametextpricenumeric
BOO-0003the art of sql29.00
BOO-0028bamboo cookbook15.50
(2 rows)

one feed row per sku: each book gets its new price.

real output, postgres 18.6 (PGlite 0.5.12) · update-delete
switch the statement and the feed. with a duplicate sku in the feed, UPDATE ... FROM picks one of the two prices without a word. MERGE, given the same feed, stops with an error.

with two feed rows for one book, the book still gets updated once, with whichever pairing the join produced first. here that was 35.00. the manual says plainly that which one wins "is not readily predictable": a different plan can pick the other. if the feed can have duplicates, deduplicate it first, or use MERGE, which refuses to change a row twice.

DELETE, and what it takes with it

DELETE is UPDATE without the SET: WHERE picks the rows, and they go. but rows have friends. orders point at customers, and order_items point at orders and products, through foreign keys. shop's order_items says ON DELETE CASCADE for its order, so deleting the cancelled orders takes their line items along:

sqldb=shop
SELECT count(*) AS items FROM order_items;
DELETE FROM orders WHERE status = 'cancelled';
SELECT count(*) AS items FROM order_items;
output, from postgres 18.6
#1 · SELECT 1
itemsint8
24942
(1 row)
#2 · DELETE 317
#3 · SELECT 1
itemsint8
24228
(1 row)

DELETE 317, and 714 line items went with them without being named. products are the other way round: order_items points at them with no ON DELETE, which means "refuse".

sqldb=shop
DELETE FROM products WHERE discontinued;
output, from postgres 18.6
ERROR 23503: update or delete on table "products" violates foreign key constraint "order_items_product_id_fkey" on table "order_items"
DETAIL: Key (id)=(8) is still referenced from table "order_items".

to really remove the 12 discontinued products, their line items have to go first. DELETE ... USING is DELETE's version of UPDATE ... FROM: it joins in the table that says which rows to pick.

sqldb=shop
DELETE FROM order_items AS oi
USING products AS p
WHERE oi.product_id = p.id AND p.discontinued;
 
DELETE FROM products WHERE discontinued;
output, from postgres 18.6
#1 · DELETE 1444
#2 · DELETE 12

1,444 line items, then the 12 products. (WHERE product_id IN (SELECT id FROM products WHERE discontinued) does the same, and is standard SQL. USING is a postgres extension; the plan is usually the same join either way.)

TRUNCATE

DELETE goes row by row: it finds each one, stamps it deleted, and leaves it on its page for VACUUM to clean up later. TRUNCATE doesn't look at rows at all.

empty it with =
empty.sql
  1. 1SELECT count(*) AS rows, pg_relation_size('order_items') AS bytes, pg_relation_filenode('order_items') AS filenode FROM order_items;
the result for nothing yet
rowsint8bytesint8filenodeoid
24942130252816438
(1 row)

order_items before anything: 24,942 rows in 1.3 MB, in the file named by its filenode.

real output, postgres 18.6 (PGlite 0.5.12) · update-delete
switch between doing nothing, DELETE and TRUNCATE on order_items (both rolled back after). after DELETE the file is exactly as big as before. after TRUNCATE it's empty, and it's a different file: the filenode changed.

TRUNCATE swaps in a new, empty file and drops the old one when the transaction commits. that makes it fast on a big table and leaves no dead rows behind, at a price:

DELETETRUNCATE
picks rows with a WHEREyesno, all or nothing
fires row triggers (ON DELETE)yesno, only ON TRUNCATE ones
leaves dead rows for VACUUMyesno
lock it takesROW EXCLUSIVE: others keep reading and writingACCESS EXCLUSIVE: everyone waits (table lock modes)
a table others point at with a foreign keychecks or cascades row by rowrefused, unless you TRUNCATE them too (or say CASCADE)
rolls backyesyes, in postgres
sqldb=shop
TRUNCATE orders;
output, from postgres 18.6
ERROR 0A000: cannot truncate a table referenced in a foreign key constraint
DETAIL: Table "order_items" references "orders".
HINT: Truncate table "order_items" at the same time, or use TRUNCATE ... CASCADE.

orders is referenced by order_items, so postgres won't empty it alone. TRUNCATE orders, order_items works, and TRUNCATE ... RESTART IDENTITY resets the id sequences too.

one level deeperwhy TRUNCATE can break a snapshot

a transaction at REPEATABLE READ that took its snapshot before the TRUNCATE committed, and hadn't touched the table yet, will find it empty afterwards, even though its snapshot says the rows should be there. the old file is gone; there's nothing left to show it. the manual calls TRUNCATE "not MVCC-safe" for exactly this reason. DELETE has no such problem: the deleted rows stay on their pages until nobody can see them anymore. (snapshots and the xmin horizon explain "nobody can see them".)

keylines

  • WHERE picks the rows. no WHERE picks all of them.
  • the tag (UPDATE 2000) is your check, so BEGIN first and read it before COMMIT.
  • SET expressions all see the row as it was before the update.
  • UPDATE ... FROM silently picks one match when the source has duplicates. MERGE errors instead.
  • TRUNCATE swaps in an empty file: instant, no dead rows, but a heavy lock and no WHERE.