Lesson 5 of 29Querying basics
Changing Data Safely
INSERT, UPDATE, DELETE, RETURNING and upserts, plus the habits that stop a missing WHERE clause from becoming an incident.
Reading data can be slow or wrong, but it cannot destroy anything. Writing can. Every experienced engineer has a story about an UPDATE that ran without its WHERE clause, a cleanup script that deleted the wrong customers, or a "quick" delete of old rows that locked a table during peak traffic. This lesson covers the statements that change data, the Postgres features that make them precise (RETURNING, upserts, UPDATE ... FROM), and the routine careful engineers follow every time they touch production data.
INSERT: name your columns
The basic form takes a column list and one or more rows:
Press Run (⌘ Enter) to see what happens.Three habits are visible here. Always list the columns. INSERT INTO products VALUES (...) depends on the column order in the table, so it breaks, or silently writes into the wrong columns, the day someone adds a column. Omitted columns get their default: stock has DEFAULT 0, and id is generated. You can also write the keyword DEFAULT in place of a value. And INSERT ... SELECT copies rows in one statement inside the database, which is far faster than reading them into Python and inserting them one at a time.
From application code, insert many rows with one parameterised statement, such as executemany in Python or a single multi-row VALUES list. One round trip per row is the write-side version of the N+1 problem.
RETURNING: get the result back in one trip
After inserting a row you usually need its generated id. Postgres lets you ask for it in the same statement:
Press Run (⌘ Enter) to see what happens.RETURNING works on INSERT, UPDATE and DELETE, and it returns the rows exactly as they were written, including defaults and values set by triggers. It saves a second query and removes the race where another request changes the row between your write and your read.
Postgres 18 extends it: in an UPDATE you can return both versions of a row, which is ideal for audit logs.
UPDATE products SET price_cents = price_cents * 9 / 10
WHERE category_id = 6
RETURNING id, old.price_cents AS before, new.price_cents AS after;Upserts: insert or update in one atomic step
A sync job receives customer records. Some are new, some already exist. The naive version checks first:
row = db.execute("SELECT id FROM customers WHERE email = ?", (email,)).fetchone()
if row is None:
db.execute("INSERT INTO customers ...") # two requests can both get here
else:
db.execute("UPDATE customers ...")Two requests running at the same moment can both see "no row" and both insert. With a UNIQUE constraint, one of them crashes; without one, you now have duplicates. The fix is to let the database decide, atomically, with INSERT ... ON CONFLICT:
Press Run (⌘ Enter) to see what happens.ON CONFLICT (email) names the unique constraint to check. If a row with that email exists, the DO UPDATE branch runs instead of the insert, and excluded refers to the row you tried to insert. DO NOTHING skips the conflicting row, and notice that RETURNING then returns no row for it. Code that expects an id back must handle that case, usually by selecting the existing row.
Details that matter at work:
- The conflict target must match a unique index or constraint.
ON CONFLICT (city)fails because nothing makescityunique. DO UPDATEcan have its ownWHERE, such asWHERE customers.updated_at < excluded.updated_at, so an old message that arrives late does not overwrite newer data.- A single statement cannot touch the same row twice. If your batch contains the same email twice, Postgres raises an error, so remove duplicates first.
MySQL spells it INSERT ... ON DUPLICATE KEY UPDATE. Postgres 15 also added the standard MERGE statement, with RETURNING since Postgres 17. MERGE is good for syncing one table from another with several match rules, but the Postgres docs point out that under concurrent inserts it can still fail with a unique violation. For a plain "insert or update this row", ON CONFLICT is the safer choice.
UPDATE: expressions, joins and the hidden traps
UPDATE changes every row the WHERE matches. Write the change as an expression on the current value whenever you can:
UPDATE products SET stock = stock - 1 WHERE id = 7 AND stock > 0;This is atomic: there is no window between reading and writing where another request can sneak in, which is the lost-update bug from PostgreSQL for Developers. The stock > 0 condition turns the update into a check as well. If the row count comes back as 0, the item was out of stock, and you tell the user.
Often the new value comes from another table. Postgres has UPDATE ... FROM, which joins in extra tables. The portable alternative is a correlated subquery:
Press Run (⌘ Enter) to see what happens.Look at the subquery: it aggregates first. If you joined order_items directly, a product that appears in two paid orders would match two rows. Postgres does not apply both: it updates the row once, using whichever joined row it meets first, and you cannot predict which. The result is silently wrong. Aggregate to one row per target, then join.
DELETE, and what foreign keys do
DELETE FROM orders WHERE status = 'cancelled' removes matching rows. To delete based on another table, Postgres has DELETE ... USING, and every database supports a subquery:
-- Postgres
DELETE FROM order_items AS oi
USING orders AS o
WHERE o.id = oi.order_id AND o.status = 'cancelled';
-- portable
DELETE FROM order_items
WHERE order_id IN (SELECT id FROM orders WHERE status = 'cancelled');Foreign keys decide what happens to rows that point at a deleted row. The default is to refuse:
Press Run (⌘ Enter) to see what happens.Ada has orders, so deleting her would leave orders pointing at nothing. Barbara has none, so her row goes. You choose the behaviour per foreign key with ON DELETE RESTRICT (or the default), ON DELETE CASCADE (delete the children too) or ON DELETE SET NULL. Cascades are convenient for true parts of a parent, such as an order's items, and dangerous on anything else, because one delete can quietly remove thousands of rows. The lesson on constraints and integrity covers the choice in depth.
The safe-change routine
When you change production data by hand, a typo costs real money. Careful engineers follow the same routine every time:
Write the WHERE first and run it as a SELECT. Check the count and look at a few rows. Is this really the set you mean?
Here is the routine catching a forgotten WHERE:
Press Run (⌘ Enter) to see what happens.The update hit all ten orders, the count did not match, and the rollback put everything back. Without BEGIN, those ten orders would have been cancelled for good, and the only fix would be restoring from a backup.
Two more habits help. Before a large change on a busy database, run SET lock_timeout = '5s' in your session, so that if the statement has to wait for a lock it gives up instead of queueing every other request behind it. And for anything bigger than a one-off fix, write the change as a reviewed script or migration rather than typing it live.
Put the steps for fixing bad data in production in the right order.
- Tap the steps below in the right order.
TRUNCATE versus DELETE
TRUNCATE orders empties a table without scanning it row by row, so it is much faster than DELETE FROM orders on a large table and frees the space immediately. It differs in ways that matter:
- It does not fire per-row
ON DELETEtriggers, and it refuses to run if other tables have foreign keys pointing at it, unless you addCASCADE, which truncates them too. - It takes the strongest lock in Postgres, blocking even reads until the transaction ends.
TRUNCATE ... RESTART IDENTITYalso resets identity sequences.- In Postgres it is transactional: inside
BEGINyou can roll it back. In MySQL it is not:TRUNCATEcauses an implicit commit and cannot be undone. SQLite has noTRUNCATE; aDELETEwithoutWHEREis optimised to do the same job.
Use TRUNCATE for staging and test tables, and DELETE when you need a filter, triggers or normal locking.
Soft deletes
Many products never really delete. They add a deleted_at timestamptz column and set it instead, which gives you undo, an audit trail, and a way to restore a customer's account. The cost is that every query must remember the filter. Miss WHERE deleted_at IS NULL in one report and deleted customers come back. Unique constraints break too: a user who deletes their account cannot sign up again with the same email, because the old row still holds it. The fix is a partial unique index that only covers live rows:
Press Run (⌘ Enter) to see what happens.Soft deletes also do not satisfy privacy law on their own. When a user asks for their data to be erased, under the GDPR for example, a hidden row is still stored data. Teams often combine both: soft delete for a grace period, then a scheduled job that deletes or anonymises the rows for real. Views or ORM default filters can hide deleted rows, but they are easy to bypass, so test the filter on your most important queries.
Big changes go in batches
"Delete all events older than a year" might be 200 million rows. As one statement it runs for a long time in a single transaction, holds row locks the whole time, generates a burst of write-ahead log that replicas fall behind on, and leaves millions of dead rows that Postgres's VACUUM must clean up later. If it fails at 90 percent, it all rolls back.
Do it in batches: a few thousand rows per transaction, committed one by one, with a short pause between them.
Press Run (⌘ Enter) to see what happens.Each batch is short, so locks are released quickly and other traffic keeps flowing. If the job dies, the finished batches stay done and you just run it again. In production you would use batches in the thousands, walk through the table by primary-key range so each batch uses the index, and watch replication lag while it runs. Locks, VACUUM and long transactions get their own lessons in the Transactions and concurrency unit.
Both emails already exist in customers. How many rows does RETURNING print?
from shopdb import connect
db = connect()
rows = db.execute("""
INSERT INTO customers (name, email, created_at)
VALUES ('A', 'ada@example.com', '2025-08-01'),
('B', 'grace@example.com', '2025-08-01')
ON CONFLICT (email) DO NOTHING
RETURNING id
""").fetchall()
print(len(rows))BEGIN; TRUNCATE staging_orders; in MySQL, realise it is the wrong table, and run ROLLBACK. What happens?UNIQUE (email). A user deletes their account, then tries to sign up again. What is the best fix?- RETURNING
- A clause on INSERT, UPDATE or DELETE that returns the written rows, such as generated ids, without a second query.
- upsert
- Insert a row, or update it if it already exists, in one atomic statement:
INSERT ... ON CONFLICT DO UPDATEin Postgres. - EXCLUDED
- In an
ON CONFLICT DO UPDATE, the row you tried to insert, so you can copy its values onto the existing row. - MERGE
- A standard statement (Postgres 15+) that inserts, updates or deletes rows of one table based on a match with another.
- TRUNCATE
- Empties a table without a row-by-row scan. Transactional in Postgres, an implicit commit in MySQL.
- soft delete
- Marking a row as deleted, usually with a
deleted_atcolumn, instead of removing it. - partial index
- An index that only covers rows matching a
WHERE, such as a unique index on live rows only.