Sub topic 11
Previewing and Running Bulk Changes Safely
This chapter assumes you can write UPDATE ... FROM and DELETE ... USING statements and know the schema from the earlier chapters (customers, orders, products, price_updates). It also assumes you can run statements in psql or another PostgreSQL client. Here you will build a repeatable routine for running bulk changes so that a wrong join condition costs you a rollback instead of a restore from backup.
Why bulk changes need a routine
A single UPDATE or DELETE with a join can touch thousands of rows in one statement. PostgreSQL does not ask for confirmation. If the join condition is wrong, or if a filter is missing, the statement succeeds and reports something like UPDATE 48213. The only warning is a row count that you have to know how to read.
The safe approach has four steps:
- Preview the affected rows with a
SELECTthat uses the same join and filter. - Run the change inside a transaction.
- Inspect the result with
RETURNINGand row counts. - Commit only when the result matches what you expected, and roll back otherwise.
Step 1: Preview with SELECT
Turn the modification into a SELECT that uses the same FROM/USING tables and the same WHERE clause. For the order-cancelling change used in this chapter, the preview looks like this:
SELECT o.id, o.customer_id, o.status, c.status AS customer_status
FROM orders AS o
JOIN customers AS c ON o.customer_id = c.id
WHERE c.status = 'closed'
AND o.status = 'open';Check two things. The first is whether the rows look right. The second is how many rows come back. A count query is often the quickest sanity check:
SELECT count(*) AS rows_to_change
FROM orders AS o
JOIN customers AS c ON o.customer_id = c.id
WHERE c.status = 'closed'
AND o.status = 'open';If you expected a few dozen closed customers' open orders and the count equals the total number of rows in orders, you have a join or filter problem. Find it before you write any UPDATE.
For an UPDATE ... FROM, the preview should also expose the multiple-match problem from the earlier chapter. Count how many source rows match each target row:
SELECT p.id, p.name, count(*) AS matching_updates
FROM products AS p
JOIN price_updates AS u ON u.product_id = p.id
GROUP BY p.id, p.name
HAVING count(*) > 1;Any row returned here means the plain UPDATE ... FROM would pick one matching staging row arbitrarily. Resolve that first, for example with the DISTINCT ON subquery shown earlier.
Step 2: Run the change inside a transaction
In psql with default settings, each statement is its own transaction and commits as soon as it finishes. BEGIN opens an explicit transaction, so nothing becomes permanent until you issue COMMIT. Until then, you can undo everything with ROLLBACK.
BEGIN;
UPDATE orders AS o
SET status = 'cancelled'
FROM customers AS c
WHERE o.customer_id = c.id
AND c.status = 'closed'
AND o.status = 'open'
RETURNING o.id, o.customer_id, o.status;
-- Check the rows returned, then:
ROLLBACK; -- or COMMIT;psql also prints a command tag after the statement, such as UPDATE 37. Compare this number with the count from your preview. They should be equal. If they differ, something changed between the preview and the run, or the two statements are not equivalent.
Two details about transactions are worth knowing:
- If any statement inside the transaction fails, PostgreSQL marks the transaction as aborted. Every later statement is rejected with
current transaction is aborted, commands ignored until end of transaction blockuntil you runROLLBACK. You cannot fix the typo and carry on in the same transaction. - A transaction that you leave open holds its locks. If you run
BEGIN, run the update, and then go to lunch, other sessions that need those rows wait for you. Decide quickly, thenCOMMITorROLLBACK.
Step 3: Inspect with RETURNING
RETURNING sends back the rows that the statement actually changed. For an UPDATE, it returns the new values. For a DELETE, it returns the values of the deleted rows. You can include columns from the joined table too, as long as it is named in FROM or USING:
BEGIN;
DELETE FROM orders AS o
USING customers AS c
WHERE o.customer_id = c.id
AND c.status = 'closed'
RETURNING o.id, o.total, c.name AS customer_name;RETURNING can only show the state after the statement. For an UPDATE, you cannot read the old value of status from RETURNING. If you need a before-and-after comparison, capture the old values first with the preview SELECT, or copy them into a temporary table:
CREATE TEMP TABLE orders_before AS
SELECT o.id, o.status
FROM orders AS o
JOIN customers AS c ON o.customer_id = c.id
WHERE c.status = 'closed'
AND o.status = 'open';A temporary table lasts for the session, and it gives you a record to compare against after the update.
Step 4: Verify, then commit or roll back
Before COMMIT, run checks inside the same transaction. Your session sees its own uncommitted changes, so a SELECT shows the post-change state:
SELECT status, count(*)
FROM orders
GROUP BY status
ORDER BY status;Ask these questions:
- Does the row count equal the preview count?
- Are rows with other statuses, or rows for other customers, unchanged?
- Do the totals match, for example the number of open orders before minus the number of cancelled orders?
- For deletes, does a foreign key from another table now point at nothing? A foreign key without
ON DELETE CASCADEwill make theDELETEfail instead, which is the safe outcome. WithON DELETE CASCADE, rows in child tables disappear too, and the command tag does not count them.
If everything checks out, run COMMIT;. If not, run ROLLBACK; and return to the preview.
Keeping a safety copy of deleted rows
A data-modifying CTE can move rows into an archive table in the same statement that deletes them. If the archive insert fails, the whole statement fails, so you never lose rows without a copy.
CREATE TABLE orders_archive (LIKE orders INCLUDING ALL);
BEGIN;
WITH removed AS (
DELETE FROM orders AS o
USING customers AS c
WHERE o.customer_id = c.id
AND c.status = 'closed'
RETURNING o.*
)
INSERT INTO orders_archive
SELECT * FROM removed;
SELECT count(*) FROM orders_archive;
COMMIT;LIKE orders INCLUDING ALL copies the column definitions, defaults, and constraints. It does not copy foreign keys. This is why the archive can keep orders whose customers no longer exist.
Common failure modes
| Mistake | What happens | How the routine catches it |
|---|---|---|
| Join condition left out | Every target row matches every source row, so all rows change | The preview count equals the table size |
| `WHERE` filter on the wrong table | Too many or too few rows change | The preview rows look wrong |
| Several source rows per target row | One value is applied arbitrarily | The `HAVING count(*) > 1` check returns rows |
| Typing `COMMIT` too early | Wrong changes become permanent | You inspect `RETURNING` and counts first |
| Forgetting `BEGIN` | The statement commits immediately | The prompt in `psql` shows no open transaction |
| Leaving the transaction open | Other sessions wait on your locks | You finish with `COMMIT` or `ROLLBACK` in the same sitting |
Habits that reduce risk further
- Run
\set AUTOCOMMIT offinpsql, or always start withBEGIN. With autocommit off,psqlopens a transaction for you on the first statement, and you have to commit explicitly. Inpsql, set\set ON_ERROR_STOP onfor scripts so that a failure stops the script instead of running the rest. - Show the transaction state in the prompt. Setting
\set PROMPT1 '%/%x%R%# 'adds*to the prompt while a transaction is open, and!after an error. - Try the statement first on a copy of the data or on a staging database when the change is large or hard to reverse.
- Write the
WHEREclause first and theSETclause second, or start with aSELECTand rewrite it. This avoids typing a statement that is valid without itsWHERE. - For very large tables, a single transaction can hold locks for a long time. The chapter on locking and batching covers how to split the work.
Putting it together
This script runs the whole routine for the price update, including the multiple-match check and a count comparison:
BEGIN;
-- 1. Expected number of products to change
SELECT count(DISTINCT u.product_id) AS expected
FROM price_updates AS u
JOIN products AS p ON p.id = u.product_id;
-- 2. Apply, using only the newest staging row per product
WITH changed AS (
UPDATE products AS p
SET price = u.new_price
FROM (
SELECT DISTINCT ON (product_id) product_id, new_price
FROM price_updates
ORDER BY product_id, created_at DESC
) AS u
WHERE u.product_id = p.id
RETURNING p.id, p.price
)
SELECT count(*) AS actually_changed FROM changed;
-- 3. Compare the two numbers, then run COMMIT; or ROLLBACK;If expected and actually_changed match, and a spot check of a few products shows the right prices, commit. If they differ, roll back and investigate.
Exercise
You run BEGIN; and then a DELETE ... USING statement. The preview SELECT predicted 120 rows, but psql prints DELETE 4500. What should you do, and what is the most likely cause?
Show answer
Run ROLLBACK; and do not commit. The statement deleted far more rows than the preview, so the delete and the preview differ. The most likely cause is a missing or wrong join condition, or a WHERE filter that was dropped when you copied the statement. Compare the two statements line by line, fix the delete, preview again, and rerun it inside a new transaction.
Exercise
Write a statement that deletes the orders of closed customers and, in the same statement, saves the deleted rows into a table named orders_archive that has the same columns as orders. Why is this safer than running a DELETE followed by a separate INSERT?
Show answer
WITH removed AS (DELETE FROM orders AS o USING customers AS c WHERE o.customerid = c.id AND c.status = 'closed' RETURNING o.*) INSERT INTO ordersarchive SELECT * FROM removed; Because it is one statement, the delete and the insert succeed or fail together. With two statements, the rows are gone after the delete, and a failure or typo in the second statement leaves them unsaved. A separate insert also cannot read rows that the earlier delete already removed.