Hard postgresql sql

How do you get the top N rows per group, such as the three best-selling products per category?

The 30 second answer

Rank rows inside each group with a window function, row_number over a partition by category ordered by sales, then keep rank three or less in an outer query. For large tables where each group is cheap to read in order from an index, a LATERAL subquery with ORDER BY and LIMIT per group can be faster, because it reads only N rows per group instead of ranking everything.

Could you say this in an interview?

From the basics. GROUP BY collapses each group into one row, so it can't return three rows per category. A window function computes a value for each row while looking at other rows in its "window", without collapsing them. The docs: a window function "performs a calculation across a set of table rows that are somehow related to the current row".

Version one: window function.

WITH sales AS (
  SELECT p.category_id, p.id AS product_id, sum(oi.quantity) AS units
  FROM order_items oi
  JOIN orders o   ON o.id = oi.order_id
  JOIN products p ON p.id = oi.product_id
  WHERE o.created_at >= DATE '2026-10-01' AND o.created_at < DATE '2026-11-01'
  GROUP BY p.category_id, p.id
), ranked AS (
  SELECT *, row_number() OVER (PARTITION BY category_id ORDER BY units DESC, product_id) AS rn
  FROM sales
)
SELECT category_id, product_id, units FROM ranked WHERE rn <= 3
ORDER BY category_id, rn;

Why an outer query: window functions are computed after WHERE, so you can't filter on rn in the same SELECT.

**row_number, rank or dense_rank?** With ties, row_number picks exactly three (the extra product_id makes it deterministic), rank can return more than three and skips numbers, dense_rank returns all products in the top three distinct values. Ask the interviewer which they want; it's a classic follow-up.

Version two: LATERAL with LIMIT. If you already have a per-product sales table and an index on (category_id, units DESC), read three rows per category straight from the index:

SELECT c.id AS category_id, t.product_id, t.units
FROM categories c
CROSS JOIN LATERAL (
  SELECT ps.product_id, ps.units FROM product_sales ps
  WHERE ps.category_id = c.id
  ORDER BY ps.units DESC LIMIT 3
) t;

Trade-offs.

  • The window version ranks every row, which is simple and fine when the groups are small or the aggregate must be computed anyway.
  • The LATERAL version is fast when there are few groups and an index matching ORDER BY, but it runs one index probe per group, so many groups and a missing index make it slow.
  • For a dashboard queried often, precompute the aggregate (materialized view) and query the small result.

Alternate interview scenarios

"Return each customer's most recent order."

row_number() OVER (PARTITION BY customer_id ORDER BY created_at DESC) = 1, or PostgreSQL's DISTINCT ON (customer_id) ... ORDER BY customer_id, created_at DESC, which is shorter and often fast with an index on (customer_id, created_at DESC).

"Find the second-highest price per brand, handling ties."

dense_rank() ... = 2, and explain why row_number or OFFSET 1 give a wrong answer with ties.

Sources (4)
  1. PostgreSQL docs: Window functions tutorialpostgresql.org
  2. PostgreSQL docs: Window functions (row_number, rank, dense_rank)postgresql.org
  3. PostgreSQL docs: Table expressions (LATERAL subqueries)postgresql.org
  4. PostgreSQL docs: SELECT (DISTINCT ON)postgresql.org