How do you run UPDATE and DELETE safely?
UPDATE and DELETE change every row selected by WHERE, and without WHERE the whole table, and the database does not ask for confirmation. The safe habit is a SELECT with the same WHERE first, then the change inside BEGIN, a check of the row count against the command tag, and only then COMMIT, or ROLLBACK on a mismatch. Clients usually run in autocommit, so without BEGIN the change cannot be undone.
SQL · Changing data and transactions
Someone ran UPDATE accounts SET status = 'blocked' and forgot WHERE. How many accounts are blocked?
On a shared environment QA wants to block two accounts of user 42 to see the error screen. A condition is missing and every account is blocked. There is no undo, because the client works in autocommit mode. This lesson is about a habit that makes such mistakes visible before the commit.
How it works and why. UPDATE and DELETE pick rows by WHERE and change every picked row. Without WHERE every row is picked. The database does not ask for confirmation: it is the same operation as for one row. The only signal after execution is the command tag with a count: UPDATE 3. After that autocommit applies: psql and most GUI clients commit every statement at once, so only what runs inside BEGIN can be rolled back. One more consequence: changed rows stay locked until the end of the transaction, and a colleague updating the same row will wait.
The data that shows the difference (the accounts table before the change: accounts 7 and 8 belong to user 42, account 9 to user 43, all with status active).
The same UPDATE without WHERE and with WHERE
| id | user_id | status |
|---|---|---|
| 7 | 42 | blocked |
| 8 | 42 | blocked |
| 9 | 43 | blocked extra |
| id | user_id | status |
|---|---|---|
| 7 | 42 | blocked |
| 8 | 42 | blocked |
| 9 | 43 | active |
The habit in four steps:
-- 1. what we will touch: expect 2 rows (7 and 8)
SELECT id, user_id, status FROM accounts WHERE user_id = 42;
BEGIN; -- 2.
UPDATE accounts SET status = 'blocked'
WHERE user_id = 42
RETURNING id, status; -- 3. shows what changed
-- UPDATE 2 <- matches the expectation
COMMIT; -- 4. or ROLLBACK;
If the tag shows UPDATE 3, run ROLLBACK and nobody sees the change. The same goes for DELETE … RETURNING *: the returned rows stay as evidence and as a source for restoring. For bigger changes, a copy can be made beforehand: CREATE TEMP TABLE bak_accounts AS SELECT * FROM accounts WHERE user_id = 42; (a temporary table disappears with the session, so for longer storage use a regular table with the date in its name).
Deleting has one more trap: related rows. DELETE FROM users WHERE id = 42 either fails with a foreign key error (update or delete on table "users" violates foreign key constraint …) or, if the relation is declared with ON DELETE CASCADE, silently deletes the accounts too. Before deleting, check the child tables with the same SELECT.
Limits and alternatives. A transaction does not save you from a change you have already committed. MySQL has the sql_safe_updates guard, which rejects UPDATE and DELETE without a key in WHERE or a LIMIT; PostgreSQL has no such mode. Turning autocommit off helps: \set AUTOCOMMIT off in psql, manual-commit mode in GUI clients. Then every change waits for an explicit COMMIT, but a forgotten COMMIT becomes a problem of its own (see mistakes).
Common mistakes.
- Running a change without
BEGINand learning about the error from the tag after the commit. WHERE user_id = 42 OR status = 'active':ORwidens the choice to every active row. When mixingANDandOR, add parentheses.- The condition
status <> 'blocked'will not touch rows withstatus = NULL: a comparison with NULL is not true. - A forgotten open
BEGIN: rows stay locked and others' updates hang. Such sessions show inpg_stat_activitywith the stateidle in transaction. - Checking the count only by eye: compare the number with the one expected from step 1.
Check yourself
The SELECT from step 1 showed 2 rows and the UPDATE inside the transaction returned UPDATE 3. What to do?
Answer
ROLLBACK and investigate. The conditions in SELECT and UPDATE may have diverged, or someone added a row in between. A count mismatch must not be committed.
In psql without BEGIN, an UPDATE ran with the tag UPDATE 3 instead of 2. Will ROLLBACK help?
Answer
No. Autocommit has already committed the change, and ROLLBACK only warns that there is no transaction. You have to restore from a copy or a backup, so the copy is needed before the change.