Sub topic 11
Previewing and Running Bulk Changes Safely
Assume you know basic SELECT, WHERE, INNER JOIN, UPDATE, and DELETE statements. You should also know PostgreSQL table aliases and how to run statements in psql or another PostgreSQL client.
A bulk modification changes many rows in one statement. The safest workflow is:
- Write the matching condition as a
SELECT. - Check how many rows match.
- Inspect representative rows.
- Run the change in a transaction.
- Use
RETURNINGto inspect the affected rows. - Commit only after the result is correct.
Preview the target rows
Suppose open orders belonging to closed customers should be cancelled. First, preview the exact rows without changing anything:
SELECT o.id, o.customer_id, o.status, c.status AS customer_status
FROM orders AS o
JOIN customers AS c
ON c.id = o.customer_id
WHERE c.status = 'closed'
AND o.status = 'open';Count the rows before modifying them:
SELECT count(*) AS rows_to_change
FROM orders AS o
JOIN customers AS c
ON c.id = o.customer_id
WHERE c.status = 'closed'
AND o.status = 'open';The JOIN and WHERE conditions in this preview should match the conditions in the final UPDATE. This makes the preview a useful check for accidental broad matches.
Use a transaction and `RETURNING`
A transaction groups statements into one unit. ROLLBACK undoes the changes. COMMIT makes them permanent.
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;
-- Inspect the returned rows in your client.
-- Use COMMIT only when the result is correct.
ROLLBACK;The example rolls back deliberately. During a real run, replace ROLLBACK with COMMIT after checking the returned rows. A RETURNING clause reports values from rows affected by the statement. It is more reliable than running a second query after the change, because the second query might see a different database state.
A repeatable safety checklist
| Check | Question |
|---|---|
| Preview | Does a matching `SELECT` show only intended rows? |
| Count | Is the number of rows plausible? |
| Join | Does every target row have the intended related row? |
| Transaction | Can you inspect the result before committing? |
| Recovery | Do you have a backup or another recovery plan for important data? |
Understand the workflow
If the operation affects a very large table, the transaction may hold locks for a long time and create a large amount of write-ahead log. Consider processing a bounded batch, checking progress, and repeating. The exact batching query depends on a stable key such as id. Do not use an arbitrary LIMIT without an ordering rule, because the selected rows may vary between runs.
Exercise
Why should the preview SELECT use the same join and filtering conditions as the final UPDATE?
Show answer
It lets you inspect the exact target set before changing it and helps reveal a missing or overly broad join condition.