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.
| idint4 | nametext | citytext |
|---|---|---|
| 1 | Maya Chen | San Francisco |
| 2 | Grace Okafor | Lagos |
| 3 | Sam Lee | Toronto |
| 4 | Zoë Martin | Paris |
| 5 | Zoe Martin | Lyon |
| 6 | José Silva | null |
| 42 | Ada Lovelace | London |
seven customers, a window into a table of 2,000.
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:
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;| idint4 | nametext | pricenumeric |
|---|---|---|
| 3 | the art of sql | 35.20 |
| 28 | bamboo cookbook | 18.59 |
| 53 | mini notebook | 168.96 |
| 54 | compact novel | 81.14 |
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:
UPDATE products SET name = sku, sku = name WHERE id = 3;
SELECT id, sku, name FROM products WHERE id = 3;| idint4 | skutext | nametext |
|---|---|---|
| 3 | the art of sql | BOO-0003 |
UPDATE products SET category = 'misc' WHERE category = NULL;UPDATE products SET category = 'misc' WHERE category = NULL;
UPDATE products SET category = 'misc' WHERE category IS NULL;BEGIN first
the habit that saves you is boring: open a transaction, run the change, read the tag, and only then decide.
BEGIN;
UPDATE customers SET city = 'Paris';
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.
- 1UPDATE products AS p
- 2SET price = f.price
- 3FROM (VALUES ('BOO-0003', 29.00), ('BOO-0028', 15.50)) AS f (sku, price)
- 4WHERE p.sku = f.sku
- 5RETURNING p.sku, p.name, p.price;
| skutext | nametext | pricenumeric |
|---|---|---|
| BOO-0003 | the art of sql | 29.00 |
| BOO-0028 | bamboo cookbook | 15.50 |
one feed row per sku: each book gets its new price.
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:
SELECT count(*) AS items FROM order_items;
DELETE FROM orders WHERE status = 'cancelled';
SELECT count(*) AS items FROM order_items;| itemsint8 |
|---|
| 24942 |
| itemsint8 |
|---|
| 24228 |
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".
DELETE FROM products WHERE discontinued;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.
DELETE FROM order_items AS oi
USING products AS p
WHERE oi.product_id = p.id AND p.discontinued;
DELETE FROM products WHERE discontinued;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.
- 1SELECT count(*) AS rows, pg_relation_size('order_items') AS bytes, pg_relation_filenode('order_items') AS filenode FROM order_items;
| rowsint8 | bytesint8 | filenodeoid |
|---|---|---|
| 24942 | 1302528 | 16438 |
order_items before anything: 24,942 rows in 1.3 MB, in the file named by its filenode.
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:
| DELETE | TRUNCATE | |
|---|---|---|
| picks rows with a WHERE | yes | no, all or nothing |
fires row triggers (ON DELETE) | yes | no, only ON TRUNCATE ones |
| leaves dead rows for VACUUM | yes | no |
| lock it takes | ROW EXCLUSIVE: others keep reading and writing | ACCESS EXCLUSIVE: everyone waits (table lock modes) |
| a table others point at with a foreign key | checks or cascades row by row | refused, unless you TRUNCATE them too (or say CASCADE) |
| rolls back | yes | yes, in postgres |
TRUNCATE orders;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.