Rolling Spend View, Dependent Inserts, and Price Change Fallout
SQL & DataModel answerLast 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 keyscust_id → customersandproduct_id → products
customers
| cust_id | name | region |
|---|---|---|
| 1 | Alice | East |
| 2 | Bob | East |
| 3 | Chen | West |
products
| product_id | name | price_usd |
|---|---|---|
| 10 | WidgetA | 20.00 |
| 11 | WidgetB | 50.00 |
| 12 | WidgetC | 100.00 |
orders
| order_id | cust_id | product_id | qty | order_date | status |
|---|---|---|---|---|---|
| 1001 | 1 | 10 | 2 | 2025-08-26 | completed |
| 1002 | 1 | 11 | 1 | 2025-08-29 | pending |
| 1003 | 2 | 12 | 1 | 2025-08-31 | completed |
| 1004 | 3 | 11 | 3 | 2025-09-01 | completed |
| 1005 | 2 | 10 | 5 | 2025-08-20 | completed |
Tasks
- View. Create a view
recent_customer_spend_7d(cust_id, name, total_spend_usd). For every customer, it reports the sum ofqty * price_usdover orders withstatus = 'completed'dated from 2025-08-26 through 2025-09-01, inclusive. - 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'. - Status update. Mark order 1002 as
'completed'. - 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core ideas
- A view is a saved query and holds no data. Each read recomputes against the current table contents.
- "For each customer" means customers with no qualifying orders must still appear, with a total of 0.
- Foreign keys dictate insertion order: parent rows before child rows.
- Every
UPDATEshould be scoped by primary key.
Part 1: the view
Use a LEFT JOIN from customers, and put the status and date predicates in the ON clause. If they were in WHERE, the NULL-extended rows for customers without matching orders would be discarded, silently turning the outer join into an inner join.
For the window, a half-open range is safer than BETWEEN. It matches BETWEEN for a DATE column but remains correct if the column later becomes a timestamp, where BETWEEN ... AND '2025-09-01' would miss orders placed after midnight on the last day.
CREATE VIEW recent_customer_spend_7d AS
SELECT
c.cust_id,
c.name,
COALESCE(SUM(o.qty * p.price_usd), 0) AS total_spend_usd
FROM customers c
LEFT JOIN orders o
ON o.cust_id = c.cust_id
AND o.status = 'completed'
AND o.order_date >= DATE '2025-08-26'
AND o.order_date < DATE '2025-09-02'
LEFT JOIN products p
ON p.product_id = o.product_id
GROUP BY c.cust_id, c.name;
COALESCE is needed because SUM over no rows is NULL. Group by cust_id (not just name), since names may repeat. In production, replace the literals with a rolling window based on CURRENT_DATE; the syntax varies by dialect. Literals are used here so the results are reproducible.
Initial output:
| cust_id | name | total_spend_usd | reason |
|---|---|---|---|
| 1 | Alice | 40.00 | order 1001 is 2 x 20; 1002 is pending |
| 2 | Bob | 100.00 | order 1003; 1005 is dated 08-20, outside the window |
| 3 | Chen | 150.00 | order 1004 is 3 x 50 |
Part 2: inserts
The product must exist before the order that references it. A transaction keeps the pair atomic.
BEGIN;
INSERT INTO products (product_id, name, price_usd)
VALUES (13, 'WidgetD', 35.00);
INSERT INTO orders (order_id, cust_id, product_id, qty, order_date, status)
VALUES (1006, 2, 13, 3, DATE '2025-09-01', 'pending');
COMMIT;
The view output is unchanged because order 1006 is still pending.
Part 3: status update
UPDATE orders SET status = 'completed' WHERE order_id = 1002;
Order 1002 is dated 2025-08-29 (inside the window) for product 11 at 50.00, so Alice becomes 40 + 50 = 90.00.
Part 4: price cut and its effect
UPDATE products
SET price_usd = ROUND(price_usd * 0.90, 2)
WHERE product_id = 11;
WidgetB drops to 45.00. Filtering on product_id rather than name avoids touching other rows, since names are not guaranteed unique.
Do the view totals change? Yes. The view joins to the current products table on every read:
- Alice: 40 + 1 x 45 = 85.00 (was 90)
- Chen: 3 x 45 = 135.00 (was 150)
- Bob: 100.00, unchanged (he bought no WidgetB)
This is a modeling flaw. Spend that has already happened should not move because the catalog price changed.
Preventing retroactive changes
Recommended: snapshot the price on the order line.
ALTER TABLE orders ADD COLUMN unit_price_usd DECIMAL(10,2);- Backfill before the price cut:
UPDATE orders o SET unit_price_usd = (SELECT p.price_usd FROM products p WHERE p.product_id = o.product_id); - Make the column
NOT NULL, and have every new order insert write the price at purchase time (for example, 35.00 for order 1006). - Redefine the view to use
SUM(o.qty * o.unit_price_usd)and drop theproductsjoin.
Order matters: backfilling after the cut would freeze the wrong historical prices.
Alternative: effective-dated price history. Create product_prices(product_id, price_usd, valid_from, valid_to). A price change closes the current row and inserts a new one. The view joins each order to the price valid on its date: o.order_date >= pp.valid_from AND (pp.valid_to IS NULL OR o.order_date < pp.valid_to). This preserves the whole timeline, which helps analytics, but costs a range join and more maintenance.
Trade-off: snapshotting is simpler, faster, and matches what most order systems do. Price history is better when you also need to analyze price changes over time.
A materialized view is not a fix. It only delays the problem until the next refresh, which then rewrites history in the same way.
Complexity
With indexes on orders(order_date) or orders(cust_id) and the primary key on products, the view costs roughly O(C + O_window) per read plus grouping. Without an index on order_date it scans all orders. The view stores nothing. Point inserts and updates by primary key are O(log n).
Common mistakes
- Putting the status or date filter in
WHERE, which drops customers with zero spend. - Forgetting
COALESCE, so idle customers show NULL. - Off-by-one windows (using
>on the start date, or an 8-day range). - Inserting the order before the product, violating the foreign key.
- An
UPDATEwithout aWHERE, repricing everything. - Using floating-point types for money instead of
DECIMALwith rounding. - Assuming a view snapshots data, or that a materialized view solves historical accuracy.
- Dirty
statusvalues; normalize withLOWER(TRIM(status))or aCHECKconstraint.