SQL Transactions and ROLLBACK
A transaction is an undo button. BEGIN, make changes, then COMMIT to keep them or ROLLBACK to discard them.
Sometimes the safest way to make a risky change is to give yourself an undo button. A transaction does exactly that: BEGIN opens it, you make your changes, and then you decide.
COMMIT makes everything since the BEGIN permanent; ROLLBACK discards all of it, as if it never happened. It's the ultimate "measure twice" tool. You can even undo a full-table delete.
begin;
update products set price = 0; -- oops
rollback; -- undo it all
-- prices are unchangedSchema · Garden ShopTable · orders6 columns · 24 rows
One row per order. Unshipped orders have a null shipped_date.
Prove that ROLLBACK is a real safety net. In one script:BEGIN a transaction, delete every order, then ROLLBACK. Finally, SELECTcount(*) of the orders as order_count. It should still be 24, because the rollback undid the delete.
- Columns: order_count.
- Rows: 1, a single count.
- The DELETE is undone by ROLLBACK, so the count is back to 24.
You finished “DML: Measure Twice, Cut Once.”
Nice work. Ready to start the next one?
Start Chapter 9: Query Debugging and Common Mistakes →Begins with 9.1 Reading error messages