BEGINNERPROJECTCHAPTER 07

Project: build and query the shop database

Load ten million rows, answer thirty business questions with correct SQL, make every one of them fast with indexes you can defend, and prove the data is consistent

180 MINDATABASESUPDATED 2026-11-02

You finish module D1 by doing the job end to end on the shop. You load the dataset, answer thirty questions a real shop asks, make each answer fast, and write down the result in two files that later modules build on. Module D2’s project diagnoses slow queries under load against the index set you record here, so make it one you can defend.

What you build

Three files, all under labs/databases/shop/queries/, all written by you:

  • d1-queries.sql: thirty queries, numbered Q1 to Q30, each preceded by a comment with the business question, the expected result shape you wrote down before running it, and the shape you got.
  • d1-indexes.sql: the final index set. Every CREATE INDEX in it names the queries it serves and carries the before-and-after buffer counts from EXPLAIN (ANALYZE, BUFFERS).
  • d1-selfcheck.sql: a script that asserts the shop’s invariants and fails loudly if any is broken.

The rules

Write the shape first. Before running a query, write in its comment what one row means (the grain), which columns come back, and how many rows to expect, as an exact count, a bound or a relation to another count (“one row per month, about 36”; “exactly as many rows as the order has items”; “0 rows”). Then run it and compare. A mismatch is a bug in the query or in your understanding of the data, and both are worth finding now.

Anchor time to the data. The loader generates three years of orders ending at a fixed point, which is not today. Every “last 30 days” in the questions below means relative to (SELECT max(created_at) FROM orders). Put it in a CTE at the top of each query that needs it, WITH now_ AS (SELECT max(created_at) AS t FROM orders), so the results do not change when you rerun them next month.

Revenue means money that arrived. Unless the question says otherwise, revenue counts orders with status paid or shipped, valued at total_cents. Cancelled orders and placed-but-unpaid orders are not revenue. Store money as integer cents and convert only for display.

An index must earn its place. Each index serves at least one named query and shows a large drop in buffers for it. Aim for 8 to 12 indexes in total beyond the primary keys and the two unique constraints. If two indexes serve the same queries, keep the one that serves more of them (the leftmost-prefix rule usually decides). Remember the write bill you measured in the indexes chapter.

The thirty questions

The questions come in five groups, the way a shop’s teams ask them. The shape column is the one you check against; counts are for scale 1 unless they are exact.

Customer

# Question Expected shape
Q1 Find a customer by email, ignoring case (support types Alice@Example.com). 1 row: id, email, name, country, created_at
Q2 A customer’s 20 most recent orders, newest first, with status and total. up to 20 rows: order id, created_at, status, total_cents
Q3 Customers who signed up in the last 30 days and have not ordered yet. one row per customer: id, email, created_at; about 800 at scale 1 (89 at 0.1)
Q4 The top 100 customers by revenue, with order count. 100 rows: id, email, orders, revenue_cents, descending
Q5 Customers per country and each country’s share of all customers. one row per country (30); shares sum to 100%; DE, NG, US, JP, GB about 70% together (69.6%)
Q6 Repeat-purchase rate by signup-month cohort: of customers who signed up in a month, the share with two or more orders. one row per signup month (48: sign-ups run from November 2022, a year before the first order): month, customers, repeaters, rate

Catalogue

# Question Expected shape
Q7 A product by SKU, with its current stock. 1 row: id, sku, name, category, price_cents, on_hand
Q8 Page 3 of a category listing, cheapest first, 20 per page, using keyset pagination (WHERE (price_cents, id) > the last row of page 2), not OFFSET. 20 rows, ordered by price_cents then id
Q9 The 10 best-selling products by units in the last 90 days. 10 rows: product id, name, units
Q10 Products that have never been ordered. one row per product: id, sku, name; 0 rows on the loaded data, and the count is the answer
Q11 The reorder list: products with fewer than 10 on hand that sold at least once in the last 30 days. rows: product id, sku, on_hand, units_last_30d
Q12 Per category: product count, median price and price range. 40 rows: category, products, median_cents, min_cents, max_cents

Orders

# Question Expected shape
Q13 The order page: one order with its items and product names. one row per item (1 to a handful): order id, status, total_cents, product name, qty, unit_price_cents
Q14 Orders still placed (not paid) more than 24 hours after creation. rows: id, customer_id, created_at, age; nearly all of the 3% of placed orders (60,070 of 60,156 at scale 1)
Q15 Late shipments: orders paid more than 3 days ago and not shipped. rows: id, customer_id, created_at
Q16 Per month: average items per order and average order value. about 36 rows: month, avg_items, avg_value_cents
Q17 Per month: median and 95th percentile hours from order to shipment. about 36 rows: month, p50_hours, p95_hours
Q18 The 10 largest orders of the latest calendar year, with customer email. 10 rows: order id, email, total_cents, created_at

Revenue

# Question Expected shape
Q19 Revenue per month over the whole dataset. about 36 rows: month, revenue_cents; growing over time
Q20 Revenue per country per quarter. at most 30 × 12 rows: country, quarter, revenue_cents
Q21 Revenue per category for the latest full month, with each category’s share. 40 rows: category, revenue_cents, share; shares sum to 100%
Q22 Month-over-month revenue growth in percent (a window function). about 36 rows: month, revenue_cents, growth_pct; the first row’s growth is NULL
Q23 Running total of revenue by day for the latest calendar year. one row per day with orders: day, revenue_cents, running_total_cents; the last running total equals that year’s revenue
Q24 Reconciliation by month: sum of captured payments against sum of order totals for paid and shipped orders. about 36 rows: month, captured_cents, orders_cents, difference; any non-zero difference explained in your comment

Operations

# Question Expected shape
Q25 Payment failure rate per provider over the last 7 days. 3 rows: provider, attempts, failed, failure_rate
Q26 Orders with more than one captured payment (possible double charges). expected 0 rows
Q27 Refunds per day over the last 30 days: count and amount. up to 30 rows: day, refunds, refunded_cents
Q28 Products whose stock would go negative if every placed and paid order shipped now. rows: product id, on_hand, reserved, shortfall
Q29 Orders per hour of day over the last 30 days, per country. at most 24 × 30 rows: country, hour, orders
Q30 Customers with 3 or more failed payments in the last 7 days (fraud review). rows: customer id, email, failed_payments; usually few or none

Some questions have traps that earlier chapters prepared you for. Q4 and Q16 fan out if you join items and payments to orders in the same query. Q3 and Q10 are anti-joins, where NOT IN with a NULL behaves differently from NOT EXISTS. Q8 with OFFSET gets slower with every page. Q24 is where you find out whether the data is consistent before the self-check tells you.

What done looks like

All thirty queries run, each comment’s expected shape matches what came back (or explains why it does not), no query in Q1, Q2, Q7, Q8, Q13 and Q14 takes more than a few milliseconds at scale 1, because those run on every page view, and the reporting queries (Q19 to Q24) finish in seconds, not minutes. d1-indexes.sql applies cleanly to a freshly loaded database, and d1-selfcheck.sql prints that all invariants hold.

LAB Thirty queries, an index set, and a self-check LONG · ~180 MIN
YOU NEEDDocker Desktop or Docker Engine with Composethe ATLAS repo cloned; labs/databases from docs/LABS.mdabout 4 GB of free disk at scale 1 (scale 0.1 for laptops under 8 GB of RAM: divide row counts by ten)a text editor for the three .sql files

Work in labs/databases. Keep two terminals open: one in psql, one in the shell for running whole files.

1. Start the stack and load the shop.

cd labs/databases
docker compose up -d
docker compose exec db psql -U atlas shop -c '\dt'

\dt lists the six tables: the first start of an empty volume applies schema.sql. Then load, at scale 1 or 0.1:

time docker compose exec -T db psql -U atlas -d shop -v scale=1 -f /shop/load.sql
docker compose exec db psql -U atlas shop -c "VACUUM ANALYZE;"
The load takes about 25 seconds at scale 1 (962 MB) and 3 seconds at scale 0.1 (102 MB) and ends by printing the row counts. If you loaded before, that is fine: load.sql truncates all six tables first. It does not drop indexes, which step 2 checks.

2. Check the data is what the schema promises.

SELECT (SELECT count(*) FROM customers)   AS customers,
       (SELECT count(*) FROM products)    AS products,
       (SELECT count(*) FROM orders)      AS orders,
       (SELECT count(*) FROM order_items) AS items,
       (SELECT count(*) FROM payments)    AS payments;
SELECT status, round(100.0 * count(*) / sum(count(*)) OVER (), 1) AS pct
FROM orders GROUP BY status ORDER BY pct DESC;
SELECT min(created_at), max(created_at) FROM orders;
SELECT indexrelid::regclass FROM pg_index WHERE indrelid::regclass::text IN
  ('customers', 'products', 'inventory', 'orders', 'order_items', 'payments');
500,000 customers, 50,000 products, 2,000,000 orders, 5,999,378 items and 2,000,000 payments at scale 1 (50,000, 5,000, 200,000, 599,833 and 200,000 at 0.1). shipped 85.0%, cancelled 7.0, paid 5.0, placed 3.0. Orders span three years, 2023-11-01 to the last minutes of 2026-10-31 UTC: the max is your “now” for every relative window. The index list holds only the six primary keys plus customers_email_key and products_sku_key; if anything else is there, an earlier chapter left it (the indexes chapter leaves orders_customer_created, orders_open and possibly order_items_order_id), so drop it with DROP INDEX name; before you measure.

3. Write the thirty queries, shape first.

Create shop/queries/d1-queries.sql. For each question, write the comment block, then the query. The format, with Q2 as the example:

-- Q2. A customer's 20 most recent orders, newest first.
-- Expected: up to 20 rows (customer_id, created_at DESC, status, total_cents).
--           For customer 4242: as many as count(*) of that customer's orders, capped at 20.
-- Got:      2 rows, newest 2026-01-29. Matches count(*) = 2. (Scale 0.1: 4 rows, newest 2026-06-30.)
SELECT id, created_at, status, total_cents
FROM orders
WHERE customer_id = 4242
ORDER BY created_at DESC
LIMIT 20;

Run the whole file with timing to see which queries are slow before you index anything:

docker compose exec -T db psql -U atlas shop -v ON_ERROR_STOP=1 -c '\timing on' -f - < shop/queries/d1-queries.sql > /tmp/d1-before.txt
grep -E '^Time:' /tmp/d1-before.txt | nl
Thirty Time: lines, numbered in query order. Without indexes, most of the lookup queries (Q1, Q2, Q13, Q14) take tens to hundreds of milliseconds at scale 1 because each one is a sequential scan, and several reporting queries take seconds. Keep this file: it is the “before” column of your evidence.

For each query, check the shape you predicted. For counts, write an independent query: Q13’s row count must equal SELECT count(*) FROM order_items WHERE order_id = ...; Q4’s revenue for the first customer must equal a separate sum(total_cents) over that customer’s paid and shipped orders.

4. Find the indexes, one query at a time.

For each query in order of how often it would run (page views first, reports last), run EXPLAIN (ANALYZE, BUFFERS), read the plan, and decide whether an index would help and which. Create it, rerun EXPLAIN, and keep it only if the buffers fall a lot.

EXPLAIN (ANALYZE, BUFFERS)
SELECT id, created_at, status, total_cents FROM orders
WHERE customer_id = 4242 ORDER BY created_at DESC LIMIT 20;

CREATE INDEX orders_customer_created ON orders (customer_id, created_at);

EXPLAIN (ANALYZE, BUFFERS)
SELECT id, created_at, status, total_cents FROM orders
WHERE customer_id = 4242 ORDER BY created_at DESC LIMIT 20;
Before: a Parallel Seq Scan plus a Sort under Gather Merge, about 18,400 shared buffers at scale 1, the whole table. After: a Bitmap Index Scan on orders_customer_created feeding a tiny Sort, under ten buffers. The planner expects a handful of rows per customer, so sorting them is cheaper than walking the index backwards; with LIMIT 3 you get Index Scan Backward and no Sort, as in the indexes chapter. That is one entry in your index file. Expect to find that Q1 needs an expression index (a plain index on email cannot serve lower(email)), that Q13 and the self-check need order_items (order_id), and that Q14 and Q15 are partial-index territory. Some reporting queries read most of a table whatever you do; the right answer for those is no index, and your file should say so.

5. Record the final index set in shop/queries/d1-indexes.sql.

The file is the answer to “why does each of these indexes exist?”. It must apply cleanly to a freshly loaded database, so use IF NOT EXISTS, and one entry per index in this form:

-- Serves: Q2, Q4 (per-customer lookups and ordering).
-- Q2 before: Parallel Seq Scan + Sort, 18,4xx buffers, 28 ms.
-- Q2 after:  Bitmap Index Scan + Sort, 8 buffers, 0.03 ms.
-- Size: 60 MB at scale 1.
CREATE INDEX IF NOT EXISTS orders_customer_created ON orders (customer_id, created_at);

End the file with a comment listing the indexes you tried and dropped, and why (made redundant by a composite, ignored by the planner, cost more on writes than it saved). Then prove it applies and is used:

docker compose exec -T db psql -U atlas shop -v ON_ERROR_STOP=1 < shop/queries/d1-indexes.sql
docker compose exec -T db psql -U atlas shop -c "SELECT pg_stat_reset();"
docker compose exec -T db psql -U atlas shop -v ON_ERROR_STOP=1 -c '\timing on' -f - < shop/queries/d1-queries.sql > /tmp/d1-after.txt
docker compose exec db psql -U atlas shop -c "SELECT relname, indexrelname, idx_scan, pg_size_pretty(pg_relation_size(indexrelid)) FROM pg_stat_user_indexes ORDER BY idx_scan;"
The index file runs with no errors and creates nothing on a second run. After one pass of the thirty queries, every index you created shows idx_scan of at least 1. An index with 0 serves none of your queries: either a query changed and the index is stale, or it never served one, and it goes. Compare /tmp/d1-before.txt with /tmp/d1-after.txt line by line: the page-view queries should be in the low milliseconds or below.

6. Write the self-check.

Create shop/queries/d1-selfcheck.sql. It asserts invariants the schema does not declare. The two the module requires are that an order’s total equals the sum of its items, and that no payment exceeds its order. Add any others you found while writing the queries:

DO $$
DECLARE bad bigint;
BEGIN
  -- 1. orders.total_cents equals the sum of its items.
  SELECT count(*) INTO bad
  FROM orders o
  LEFT JOIN (SELECT order_id, sum(qty * unit_price_cents) AS items_cents
             FROM order_items GROUP BY order_id) i ON i.order_id = o.id
  WHERE o.total_cents <> coalesce(i.items_cents, 0);
  ASSERT bad = 0, format('%s orders whose total_cents differs from the sum of their items', bad);

  -- 2. No single payment exceeds its order's total.
  SELECT count(*) INTO bad
  FROM payments p JOIN orders o ON o.id = p.order_id
  WHERE p.amount_cents > o.total_cents;
  ASSERT bad = 0, format('%s payments larger than their order', bad);

  -- 3. Money taken for an order (authorised or captured) never exceeds its total.
  SELECT count(*) INTO bad
  FROM (SELECT order_id, sum(amount_cents) AS taken
        FROM payments WHERE status IN ('authorised', 'captured')
        GROUP BY order_id) t
  JOIN orders o ON o.id = t.order_id
  WHERE t.taken > o.total_cents;
  ASSERT bad = 0, format('%s orders with more money taken than their total', bad);

  -- 4. Shipped orders have a shipment time, and it is not before the order.
  SELECT count(*) INTO bad FROM orders
  WHERE (status = 'shipped' AND shipped_at IS NULL) OR shipped_at < created_at;
  ASSERT bad = 0, format('%s orders with a missing or impossible shipped_at', bad);

  -- 5. Stock is never negative.
  SELECT count(*) INTO bad FROM inventory WHERE on_hand < 0;
  ASSERT bad = 0, format('%s products with negative stock', bad);

  RAISE NOTICE 'all invariants hold';
END $$;
time docker compose exec -T db psql -U atlas shop -v ON_ERROR_STOP=1 < shop/queries/d1-selfcheck.sql
NOTICE: all invariants hold and DO, in about 5 seconds at scale 1 and under one at 0.1: each check reads each table once with a hash join or aggregate. If an assertion fails, psql prints ERROR: ... orders whose total_cents differs ... with the count, and exits with status 3, which is what a CI job needs. Write check 1 instead as a correlated subquery, WHERE o.total_cents <> (SELECT sum(...) FROM order_items i WHERE i.order_id = o.id), before order_items (order_id) is indexed, and it runs for many minutes even at scale 0.1: one scan of order_items per order.
Break an invariant and an index, and watch each tool catch it. First, in psql: BEGIN; UPDATE orders SET total_cents = total_cents + 1 WHERE id = 42;, then paste the self-check’s DO block into the same session. It fails with 1 orders whose total_cents differs from the sum of their items; ROLLBACK; and it passes again. That is how the self-check would catch a checkout bug that rounds a discount differently from the line items. Second, drop the index that serves Q13, order_items (order_id), and rerun the query file with timing: Q13 goes from well under a millisecond to a parallel scan of six million rows, and the self-check’s correlated variant becomes unusable. Recreate the index from d1-indexes.sql, which is what the file is for.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Storage: pages, heaps, tuples and the buffer pool →