The 30 second answer
I restate the output and edge cases first: which month, revenue definition, cancelled orders, categories with no sales. Then I build it in steps with CTEs: filter orders by a half-open date range, join items and products, group by category, use HAVING for the minimum order count, and a window for share of total. Finally I check EXPLAIN, index the date and join columns, and precompute if it runs often.
The prompt. "For October 2026, per category: number of orders, revenue, average order value and the category's share of total revenue. Exclude cancelled orders. Only categories with at least 50 orders. Sort by revenue."
Step one: ask before writing. Interviewers grade this as much as the SQL.
- Does an order with items in two categories count once per category? (Here: yes.)
- Revenue = quantity times unit price at order time, not today's product price.
- Time zone for "October"? Store timestamps as
timestamptzand define the boundaries explicitly. - Show categories with zero orders? (With the minimum of 50, no.)
Step two: build it in readable steps.
WITH oct_orders AS (
SELECT id FROM orders
WHERE status <> 'CANCELLED'
AND created_at >= TIMESTAMPTZ '2026-10-01 00:00 Europe/Berlin'
AND created_at < TIMESTAMPTZ '2026-11-01 00:00 Europe/Berlin'
), lines AS (
SELECT p.category_id, oi.order_id, oi.quantity * oi.unit_price AS amount
FROM order_items oi
JOIN oct_orders o ON o.id = oi.order_id
JOIN products p ON p.id = oi.product_id
), per_category AS (
SELECT category_id,
count(DISTINCT order_id) AS orders,
sum(amount) AS revenue
FROM lines
GROUP BY category_id
HAVING count(DISTINCT order_id) >= 50
)
SELECT c.name,
pc.orders,
pc.revenue,
round(pc.revenue / pc.orders, 2) AS avg_order_value,
round(100.0 * pc.revenue / sum(pc.revenue) OVER (), 2) AS revenue_share_pct
FROM per_category pc
JOIN categories c ON c.id = pc.category_id
ORDER BY pc.revenue DESC;Points to say while writing:
- Half-open date range on the raw column, not
date_truncor a cast, so an index oncreated_atcan be used. - **
count(DISTINCT order_id)**, because joining items multiplies orders. - **
HAVING** filters groups after aggregation;WHEREfilters rows before. The grouping page covers the semantics. - **
sum(...) OVER ()** computes the grand total without a second query. Note the share is of qualifying categories only; ask if that's what's wanted.
Step three: make it fast.
CREATE INDEX orders_created_status ON orders (created_at) INCLUDE (status);
CREATE INDEX order_items_order ON order_items (order_id) INCLUDE (product_id, quantity, unit_price);Then check EXPLAIN (ANALYZE, BUFFERS): the orders scan should use the date index, the join to order_items should be a hash join or an index nested loop depending on the month's size, and there should be no disk sort for the DISTINCT counts. If the report runs many times a day, precompute daily per-category aggregates and sum those, since daily totals don't change once a day is closed (apart from late cancellations, which need a correction rule).
Trade-offs.
- One big query is easy to ship but hard to test. CTEs make each step checkable on its own. Since PostgreSQL 12, a side-effect-free CTE referenced only once is folded into the parent query by default, so readability rarely costs performance.
- Exact
count(DISTINCT ...)needs sorting or hashing; at very large scale, precomputation is the real fix.
Alternate interview scenarios
"Now add month-over-month growth per category."
Aggregate per category and month for two months, then use lag(revenue) OVER (PARTITION BY category_id ORDER BY month).
"The report must include categories with no sales as zero."
Start from categories and LEFT JOIN the aggregate, with coalesce(revenue, 0), and drop the HAVING, since a minimum would remove them again.
Sources (4)
- PostgreSQL docs: Table expressions (GROUP BY and HAVING)postgresql.org
- PostgreSQL docs: Aggregate functionspostgresql.org
- PostgreSQL docs: Window functions tutorialpostgresql.org
- PostgreSQL docs: WITH queries (CTE inlining)postgresql.org