Optimize a customer-order query on a large dataset

Instruction: Assume PostgreSQL customers(customer_id integer PRIMARY KEY) and orders(order_id bigint PRIMARY KEY, customer_id integer NOT NULL REFERENCES customers, ordered_at timestamp NOT NULL). The query is SELECT DISTINCT c.customer_id FROM customers c JOIN orders o ON o.customer_id=c.customer_id WHERE o.ordered_at >= TIMESTAMP '2026-01-01' AND o.ordered_at < TIMESTAMP '2026-02-01'. Propose an equivalent rewrite and candidate index strategy for a billion-row orders table. Explain the measurements needed before claiming a speedup.

Context: This exercise tests result-preserving query rewriting and evidence-based index/plan analysis on a large PostgreSQL order table.

Updated

Official answer

The starting query finds each customer with at least one January order. Since only customer IDs are required, an existence query expresses the intent without producing duplicate join rows:

SELECT c.customer_id
FROM customers AS c
WHERE EXISTS (
  SELECT 1 FROM orders AS o
  WHERE o.customer_id = c.customer_id
    AND o.ordered_at >= TIMESTAMP '2026-01-01'
    AND o.ordered_at < TIMESTAMP '2026-02-01'
)
ORDER BY c.customer_id;

This is a candidate rewrite, not a guaranteed speedup. Depending on selectivity and plan, an orders index beginning with customer_id then ordered_at, or one favoring the date range, may be useful. Existing indexes, table layout and write costs matter; do not add both blindly.

Compare equivalent results on customers with zero, one and several orders and exact date boundaries. Inspect estimates versus actual rows, scans, repeated loops, buffers, spills and time under representative parameters. PostgreSQL EXPLAIN ANALYZE runs the query, so use a safe environment for an expensive billion-row case.

Update inaccurate statistics or address the demonstrated bottleneck, then measure again. DISTINCT, joins and subqueries are not inherently slow or fast. Without the actual data distribution, indexes, plan and hardware, no specific latency improvement can be claimed.

Related Questions