SQL Transactions and ROLLBACK
A transaction lets you group changes and either commit them together or roll them back before they are committed.
Sometimes the safest way to make a risky change is to keep it reversible
until you have checked the result. A transaction gives you
that boundary:
BEGIN
opens it, you make your changes, and then you decide.
COMMIT
makes the transaction's changes permanent;
ROLLBACK
discards the transaction's uncommitted changes. In DuckDB, that includes the
full-table delete used in this exercise. Transaction and recovery behavior
varies across database systems and statement types, so don't treat rollback
as a substitute for backups or change controls.
begin;
update products set price = 0; -- oops
rollback; -- undo it all
-- prices are unchanged Schema · Garden Shop Table · orders 6 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, SELECT count(*) of the orders as order_count. It should
still be 24, because the rollback undid the delete.
Run your query to inspect the result.
Expected answer
- Columns: order_count.
- Rows: 1, a single count.
- The DELETE is undone by ROLLBACK, so the count is back to 24.
Related
A checklist for changing the right rows.
Searched and simple CASE, plus conditional aggregation.
Declare columns, types, defaults, and constraints.
NOT NULL, DEFAULT, CHECK, UNIQUE, and keys.
Understand INSERT, UPDATE, and DELETE.
Add rows and confirm they landed.