Full Byte Developer.

Before you run UPDATE or DELETE in production: 5 steps

Forgot the WHERE clause? With this routine it is still undoable.

Published here · 6 sources

One UPDATE or DELETE without a WHERE clause changes every row in the table. Once it commits there is no undo. The count first routine keeps it undoable.

1. Count first

Run SELECT count(*) with the exact WHERE you plan to use [1].

sql
SELECT count(*) FROM users WHERE active = false;

2. BEGIN yourself

psql and the mysql client commit every statement on their own unless you open a transaction [2]. Using a GUI? Check its autocommit setting.

sql
BEGIN;

3. Run it and check the output

Postgres and SQLite 3.35+ support RETURNING id. Count the rows it lists [1][4]. psql also prints DELETE n or UPDATE n.

sql
DELETE FROM users WHERE active = false RETURNING id;

MySQL has no RETURNING. Read the rows affected line or call SELECT ROW_COUNT();. For UPDATE it counts only rows whose value changed, so it can be lower than your count [5].

4. Commit or rollback

Count matches? COMMIT;. Anything else? ROLLBACK;. Decide fast: the rows you touched stay locked until the transaction ends [2].

sql
COMMIT;   -- only if the count matches
ROLLBACK; -- otherwise

5. Use safe mode in MySQL

Start the client with --safe-updates so UPDATE and DELETE error out unless the WHERE uses a key column or you add a LIMIT [5].

bash
mysql --safe-updates

What ROLLBACK cannot undo

ROLLBACK cannot undo a statement that already committed. In MySQL, TRUNCATE TABLE and other DDL commit on their own [6].

Send this to the teammate who runs DELETE in production without a WHERE clause safety net.

Keep this guide

By Full Byte Developer

Filed under Dev tools

Questions about this guide

Why does MySQL UPDATE count fewer rows?

MySQL counts only rows whose value actually changed, so it can be lower than your SELECT count.

Can I undo TRUNCATE TABLE in MySQL?

No. TRUNCATE TABLE and other DDL commit on their own.

Sources

  1. PostgreSQL docs: psqlpostgresql.org
  2. MySQL docs: tipsdev.mysql.com

Next in this stack