Design and Query a Retail Order Database
SQL & DataModel answerLast updated
Build a PostgreSQL schema for orders, write insert statements, compute revenue aggregates with outer joins, filter recent purchases, and update coupon fields.
You are building a retail order tracking system in PostgreSQL. Complete the following tasks:
Part 1: Schema Definition
Define four tables with appropriate data types and constraints:
- customers: customer_id (primary key), email (unique, required), created_at (required date)
- products: product_id (primary key), name (required), category (required), price (two decimal places, must be positive)
- orders: order_id (primary key), customer_id (foreign key to customers), order_date (required date), status (required, must be 'paid', 'refunded', or 'cancelled'), coupon_code (optional text)
- order_items: composite primary key on (order_id, product_id), order_id (foreign key to orders with cascade delete), product_id (foreign key to products), qty (required positive integer), unit_price (two decimal places, must be positive)
Choose minimal correct types for each column.
Part 2: Data Loading
Insert the exact rows shown in these tables:
customers
customer_id | email | created_at
----------- | ------------------- | ----------
1 | [email protected] | 2025-08-20
2 | [email protected] | 2025-08-28
3 | [email protected] | 2025-08-30
products
product_id | name | category | price
---------- | ------ | -------- | ------
10 | Widget | hardware | 25.00
11 | Gizmo | hardware | 40.00
12 | Course | digital | 199.00
orders
order_id | customer_id | order_date | status | coupon_code
-------- | ----------- | ---------- | --------- | -----------
100 | 1 | 2025-08-29 | paid | NULL
101 | 1 | 2025-09-01 | refunded | NULL
102 | 2 | 2025-08-31 | paid | SUMMER10
103 | 3 | 2025-09-01 | cancelled | NULL
104 | 1 | 2025-08-25 | paid | NULL
order_items
order_id | product_id | qty | unit_price
-------- | ---------- | --- | ----------
100 | 10 | 2 | 25.00
100 | 11 | 1 | 40.00
101 | 12 | 1 | 199.00
102 | 10 | 1 | 25.00
103 | 11 | 2 | 40.00
104 | 10 | 1 | 25.00
104 | 11 | 1 | 40.00
Part 3: Revenue Report
Write a query that calculates total revenue per customer from paid orders placed during August 2025 (inclusive of both 2025-08-01 and 2025-08-31). Revenue equals the sum of (qty × unit_price) across all items in qualifying orders.
Return columns: customer_id, email, revenue_aug2025
Include all customers in the output, showing 0 for those with no qualifying revenue. Sort by revenue descending, then by customer_id ascending.
Part 4: Recent Product Orders
Assume today's date is 2025-09-01. Write a query that finds all products that appear in orders placed within the last 7 days (from 2025-08-26 through 2025-09-01, inclusive). Exclude orders with status 'refunded' or 'cancelled'.
Return columns: product_id, name, first_order_date_in_window
Show the earliest order date in the window for each product. Each product should appear at most once.
Part 5: Coupon Backfill
Write an UPDATE statement that sets coupon_code to 'NONE' for all paid orders from August 2025 that currently have a NULL coupon_code.
Then write a SELECT query that verifies the update by counting how many rows still match the original condition (paid, August 2025, NULL coupon).
Hints
Hint 1
Create tables in dependency order: parent tables before children that reference them.
Hint 2
For the revenue query, use LEFT JOIN to preserve customers with zero revenue. Apply date and status filters in a subquery, not in the outer WHERE clause.
Hint 3
The recent products query needs GROUP BY with MIN to find the first occurrence per product and eliminate duplicates.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem tests schema definition, data manipulation, and query composition across five distinct tasks. The core challenges are understanding foreign key dependencies, correctly preserving rows with outer joins, and writing idempotent updates.
Schema Construction
Tables must be created in dependency order. Foreign keys can only reference tables that already exist, so the sequence is: customers → products → orders → order_items.
Choose INTEGER for primary keys since we're inserting explicit IDs. Use NUMERIC(10,2) for monetary amounts—never FLOAT or REAL, which introduce rounding errors. Use TEXT for variable-length strings. The status column benefits from a CHECK constraint to enforce valid values at the database level.
The cascade delete on order_items ensures that deleting an order automatically removes its line items, maintaining referential integrity without orphaned records.
Revenue Aggregation (Query A)
The requirement to include all customers, even those with zero revenue, demands a LEFT JOIN from customers to a pre-aggregated revenue subquery. A common mistake is applying the status and date filters in the outer query's WHERE clause, which converts the LEFT JOIN into an INNER JOIN and silently drops customers with no qualifying orders.
Instead, compute revenue in a CTE that filters for paid status and August dates, aggregate by customer, then LEFT JOIN this result to the full customer list. Use COALESCE to replace NULL (which SUM returns for empty groups) with 0.
On the sample data:
- Customer 1 has two paid August orders (100 and 104) totaling 155.00
- Customer 2 has one (102) totaling 25.00
- Customer 3 has no paid August orders, yielding 0.00
Recent Products (Query B)
This query requires filtering by date range and status, then grouping by product to find the earliest qualifying order date. The 7-day window ending on 2025-09-01 spans 2025-08-26 through 2025-09-01 inclusive.
Join orders to order_items to products, filter for the date window and exclude refunded/cancelled orders, then GROUP BY product with MIN(order_date). This automatically deduplicates products that appear in multiple orders.
On the sample data, orders 100 and 102 fall within the window and are not refunded/cancelled. Order 104 is one day too early (08-25). Products 10 and 11 both appear, each first ordered on 08-29.
Coupon Update (Part 5)
The UPDATE should precisely target paid August orders with NULL coupons. On the sample data, this matches orders 100 and 104, affecting 2 rows. Order 102 already has a coupon and is unchanged.
The verification query uses the identical WHERE clause to count remaining matches. After the update, this count should be zero, confirming the operation completed successfully. This pattern makes the operation testable and re-runnable.
Edge Cases
- NULL handling: NOT IN is safe here because status is NOT NULL. On nullable columns, NOT IN with NULLs produces unexpected results.
- Date boundaries: BETWEEN works correctly for DATE columns. For TIMESTAMP columns, prefer half-open ranges to avoid boundary ambiguity.
- Re-execution: Running the UPDATE twice affects 0 rows the second time because coupon_code is no longer NULL.
- Type precision: NUMERIC preserves exact decimal values; casting the COALESCE result ensures consistent output formatting.
Complexity
- Query A: O(C + O + I) time where C, O, I are row counts for customers, orders, and order_items. Hash joins and aggregation are linear in the input size. Space is O(C) for the aggregated results.
- Query B: O(O + I + P) time, O(P) space for the grouped products.
- UPDATE: O(O) scan of the orders table.
At scale, add a composite index on orders(status, order_date) to accelerate all three queries. The existing primary key on order_items already supports the joins.
Code
-- Schema
DROP TABLE IF EXISTS order_items, orders, products, customers;
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
created_at DATE NOT NULL
);
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
category TEXT NOT NULL,
price NUMERIC(10,2) NOT NULL CHECK (price > 0)
);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers(customer_id),
order_date DATE NOT NULL,
status TEXT NOT NULL CHECK (status IN ('paid', 'refunded', 'cancelled')),
coupon_code TEXT
);
CREATE TABLE order_items (
order_id INTEGER NOT NULL REFERENCES orders(order_id) ON DELETE CASCADE,
product_id INTEGER NOT NULL REFERENCES products(product_id),
qty INTEGER NOT NULL CHECK (qty > 0),
unit_price NUMERIC(10,2) NOT NULL CHECK (unit_price > 0),
PRIMARY KEY (order_id, product_id)
);
-- Data
INSERT INTO customers VALUES
(1, '[email protected]', '2025-08-20'),
(2, '[email protected]', '2025-08-28'),
(3, '[email protected]', '2025-08-30');
INSERT INTO products VALUES
(10, 'Widget', 'hardware', 25.00),
(11, 'Gizmo', 'hardware', 40.00),
(12, 'Course', 'digital', 199.00);
INSERT INTO orders VALUES
(100, 1, '2025-08-29', 'paid', NULL),
(101, 1, '2025-09-01', 'refunded', NULL),
(102, 2, '2025-08-31', 'paid', 'SUMMER10'),
(103, 3, '2025-09-01', 'cancelled', NULL),
(104, 1, '2025-08-25', 'paid', NULL);
INSERT INTO order_items VALUES
(100, 10, 2, 25.00),
(100, 11, 1, 40.00),
(101, 12, 1, 199.00),
(102, 10, 1, 25.00),
(103, 11, 2, 40.00),
(104, 10, 1, 25.00),
(104, 11, 1, 40.00);
-- Query A: August revenue per customer
WITH august_revenue AS (
SELECT o.customer_id,
SUM(oi.qty * oi.unit_price) AS revenue
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status = 'paid'
AND o.order_date BETWEEN '2025-08-01' AND '2025-08-31'
GROUP BY o.customer_id
)
SELECT c.customer_id,
c.email,
COALESCE(ar.revenue, 0)::NUMERIC(12,2) AS revenue_aug2025
FROM customers c
LEFT JOIN august_revenue ar ON ar.customer_id = c.customer_id
ORDER BY revenue_aug2025 DESC, c.customer_id;
-- Query B: Products ordered in last 7 days
SELECT p.product_id,
p.name,
MIN(o.order_date) AS first_order_date_in_window
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id
WHERE o.order_date BETWEEN '2025-08-26' AND '2025-09-01'
AND o.status NOT IN ('refunded', 'cancelled')
GROUP BY p.product_id, p.name
ORDER BY p.product_id;
-- Update: Backfill missing coupons
UPDATE orders
SET coupon_code = 'NONE'
WHERE status = 'paid'
AND order_date BETWEEN '2025-08-01' AND '2025-08-31'
AND coupon_code IS NULL;
-- Verification: Count remaining NULL coupons
SELECT COUNT(*) AS remaining_nulls
FROM orders
WHERE status = 'paid'
AND order_date BETWEEN '2025-08-01' AND '2025-08-31'
AND coupon_code IS NULL;