Safe SQL UPDATE & DELETE
Preview rows, check dependencies, and use transactions to reduce the risk of changing more rows than you intended.
UPDATE and DELETE modify stored data. One of the
most common and painful mistakes is forgetting the WHERE clause
when a change was meant to target only some rows; without it, the statement
affects every row in the table.
The checklist
- Write the
WHEREclause as aSELECTfirst. - Confirm the row count is what you expect.
- Eyeball a few of the matched rows.
- Run the change inside a transaction when possible.
- Re-check the affected row count.
-
COMMITonly once you're satisfied. OtherwiseROLLBACK.
Preview first
select *
from orders
where status = 'cancelled'
and order_date < date '2023-01-01' Then change exactly those rows
delete from orders
where status = 'cancelled'
and order_date < date '2023-01-01' Wrap risky changes in a transaction
begin;
update products
set price = price * 1.10
where category_id = 2;
-- check the result, then keep or undo:
-- commit;
-- rollback;
A bare UPDATE products SET price = 0; with no
WHERE resets every product. Previewing the target rows with a
matching SELECT before a destructive statement is a simple way
to catch many accidental broad updates or deletes.
In the SQLShed Playground, all data lives in a disposable in-browser database. Experiment freely, then reload to reset. On a persistent database, committed changes can be difficult to undo, so verify destructive statements before committing them.
Related
Understand INSERT, UPDATE, and DELETE.
Searched and simple CASE, plus conditional aggregation.
ROW_NUMBER() needs an ORDER BY that says which row wins.
Add rows and confirm they landed.
Change existing rows safely.
Declare columns, types, defaults, and constraints.