Why it happens: UPDATE or DELETE modifies too many rows
UPDATE orders
SET status = 'shipped';The teaching database currently has 18 orders. That statement has no filter, so all 18 become candidates for the update.
Important: “Without WHERE” does not mean “invalid syntax”. The engine cannot guess that you meant to change a single row.
How to fix it in SQL
Reversible example: order 102 only
First we check the target:
SELECT id, status
FROM orders
WHERE id = 102;| id | status |
|---|---|
| 102 | pending |
In SQLite and PostgreSQL, a practice run you can roll back can be written like this:
BEGIN;
UPDATE orders
SET status = 'shipped'
WHERE id = 102;
SELECT id, status
FROM orders
WHERE id = 102;
ROLLBACK;Inside the transaction, the order shows as shipped. After ROLLBACK, it goes back to pending. The syntax for starting a transaction differs between engines; use the form your engine documents.
DELETE needs the same discipline
DELETE FROM payments;Without WHERE, every row in payments are candidates. PostgreSQL explicitly documents that the absence of WHERE in DELETE deletes every row. Even if that really is the intent, it is still wise to check dependencies, permissions, backups and transactional behaviour before running it in production.
How to check it
Compare the selected ids with the changed ones and check that ROLLBACK undoes the rehearsal.
How to avoid it next time
If the change has already been committed, ROLLBACK is not enough: look at your engine's recovery options.
Related cases worth checking
If you have already run the statement
Whether you can recover data depends on the state of the transaction, the engine, the configuration and whether the change has already been committed. If the operation is still inside a transaction you can roll back and you have not yet run COMMIT, ROLLBACK can undo that transaction's changes. After committing, do not assume there is a universal “undo”: the procedure may need a backup, a point-in-time restore, logs or system-specific tools.
Carrying on running commands while unsure of the scope
If you have just made an unexpected change, avoid piling on new changes “to fix it” without understanding the current state. First work out whether the transaction is still open and which recovery mechanism your engine offers.
Compatibility and transactions
The idea of limiting the scope with WHERE is common, but transaction syntax and the ability to roll back are not identical across engines or statements. For example, some DDL statements can trigger implicit commits on certain products. For real operations, check your engine's documentation and the specific configuration.