// SQL snippet

Top-N rows per group

Keep the first N rows of every group, ranked by any column, without losing the other columns.

Main statement
All engines

The task

You want each customer's three most recent orders. A plain GROUP BY collapses the rows and a correlated subquery re-scans the table for every customer.

The snippet

Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.

All engines
WITH ranked AS (
  SELECT id, customer_id, order_date, amount,
         ROW_NUMBER() OVER (PARTITION BY customer_id
                            ORDER BY order_date DESC, id DESC) AS rn
  FROM orders
)
SELECT id, customer_id, order_date, amount
FROM ranked
WHERE rn <= 3
ORDER BY customer_id, order_date DESC;

仕組み

ROW_NUMBER numbers each customer's orders newest-first. The outer query keeps the rows numbered 1 to 3, so you get exactly three rows per customer with all columns intact. An index on (customer_id, order_date DESC) lets most engines stream this without sorting each partition.

Variations

Top-N by amount instead of recency

WITH ranked AS (
  SELECT id, customer_id, amount,
         ROW_NUMBER() OVER (PARTITION BY customer_id
                            ORDER BY amount DESC) AS rn
  FROM orders
)
SELECT id, customer_id, amount
FROM ranked
WHERE rn <= 3
ORDER BY customer_id, amount DESC;

Correlated subquery (any engine, MySQL 5.7 included)

MySQL
SELECT o.*
FROM orders o
WHERE (
  SELECT COUNT(*)
  FROM orders o2
  WHERE o2.customer_id = o.customer_id
    AND (o2.order_date > o.order_date
         OR (o2.order_date = o.order_date AND o2.id > o.id))
) < 3;

Questions that come up

Why ROW_NUMBER and not RANK?

ROW_NUMBER gives every row a different number, so you always get at most N rows per group. RANK would give tied rows the same rank and could return more than N rows when amounts or dates are equal.

Can I do this without a CTE?

You can swap the CTE for a derived table (FROM (SELECT ...) ranked), but you cannot drop the subquery: a window function is evaluated after WHERE, so WHERE ROW_NUMBER() OVER (...) <= 3 is rejected on every engine. Snowflake and DuckDB add a QUALIFY clause for exactly this; none of the five engines covered here has it.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.