KatInterview

Rolling Spend View, Dependent Inserts, and Price Change Fallout

SQL & DataModel answer
MediumModel answerSQL & Datasqlviewsleft-join

Last updated

Build a 7-day spend view over three tables, add rows in foreign-key order, update statuses and prices, then reason about how a price change distorts past spend.

Assume the current date is 2025-09-01. You have the following schema and sample data.

Schema

  • customers(cust_id INT PRIMARY KEY, name TEXT, region TEXT)
  • products(product_id INT PRIMARY KEY, name TEXT, price_usd DECIMAL(10,2))
  • orders(order_id INT PRIMARY KEY, cust_id INT, product_id INT, qty INT, order_date DATE, status TEXT), with foreign keys cust_id → customers and product_id → products

customers

cust_idnameregion
1AliceEast
2BobEast
3ChenWest

products

product_idnameprice_usd
10WidgetA20.00
11WidgetB50.00
12WidgetC100.00

orders

order_idcust_idproduct_idqtyorder_datestatus
100111022025-08-26completed
100211112025-08-29pending
100321212025-08-31completed
100431132025-09-01completed
100521052025-08-20completed

Tasks

  1. View. Create a view recent_customer_spend_7d(cust_id, name, total_spend_usd). For every customer, it reports the sum of qty * price_usd over orders with status = 'completed' dated from 2025-08-26 through 2025-09-01, inclusive.
  2. Inserts. Add a product (13, 'WidgetD', 35.00). Then add order 1006 for customer 2: 3 units of product 13, dated 2025-09-01, status 'pending'.
  3. Status update. Mark order 1002 as 'completed'.
  4. Price cut. Reduce the price of WidgetB (product_id = 11) by 10%. Explain whether the values returned by your view change as a result, and describe one SQL-compatible design that prevents past spend from being rewritten. You only need to describe the DDL precisely, not run it.

Expected: the SQL for each part, the view's output after each step, and a clear explanation for the last part.

Hints

Hint 1

The view should list every customer, including ones with no qualifying orders. Think about which join type achieves that and where the status and date conditions must live so they do not cancel it out.

Hint 2

A view stores a query, not rows. Ask yourself which price the join reads each time the view is queried, and trace Alice's and Chen's totals before and after the price cut.

Hint 3

To freeze history, record the price paid on the order line itself (and backfill it before changing any price), or keep a dated price history table and join on the order date.