Hard Writes & indexes Premium

SQL interview question: UPDATE From Another Table

Rebuild the Order Totals

An outage corrupted some order totals. The source of truth is order_items: each order's true total is the sum of quantity times the product's current price.

Write a single UPDATE statement recomputing total_amount for every order that has order_items, rounded to 2 decimals. Orders without items must keep their existing total.

Note: Your change is verified automatically (spot-checking the first orders) and rolled back afterwards.

This challenge changes data. Your statement runs on a private copy of the database, then we check the resulting table.

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
products 20 rows
  • product_id integer PK
  • product_name text
  • category text
  • price real
  • rating real
product_idproduct_namecategorypricerating
1MacBook ProElectronics1999.994.8
2iPad AirElectronics599.994.8
3AirPods ProElectronics249.994.7

Keep going