Medium Transactions Premium

SQL interview question: Two Changes in One Transaction

Cancel the Order, Cleanly

A customer cancelled order 12 before it shipped. Cancelling means two things at once: its order_items rows are removed, and the order's status becomes 'cancelled' with total_amount set to 0. A crash in between would leave a ghost order.

Write a transaction doing both, then COMMIT.

Note: Multiple statements allowed. Forgetting COMMIT discards the work. Runs on a scratch copy.

Tables

orders 15 rows
  • order_id integer PK
  • customer_id integer → customers
  • order_date text
  • total_amount real
  • status text
order_idcustomer_idorder_datetotal_amountstatus
11012024-01-20249.99delivered
21012024-03-151999.99delivered
41012024-09-0579.99delivered
order_items 19 rows
  • id integer PK
  • order_id integer → orders
  • product_id integer → products
  • quantity integer
idorder_idproduct_idquantity
1131
2211
3261

Keep going