// window reference

SQL top N rows per group

Rank rows within each partition with ROW_NUMBER, then filter rn <= N in an outer query, the standard replacement for the unsupported 'LIMIT per group'.

Categoría
Ventana
Returns
N rows per group
In this category
28 of 79

Sintaxis

WITH r AS (SELECT ..., ROW_NUMBER() OVER (PARTITION BY g ORDER BY x DESC) AS rn FROM t)
SELECT * FROM r WHERE rn <= N

Soporte del motor

MotorSupportNotas
SQL Server Sí Supported under this name.
PostgreSQL Sí Supported under this name.
MySQL Sí MySQL 8.0+
SQLite Sí SQLite 3.25+
Oracle Sí Supported under this name.

Ejemplos

Any engine

-- three biggest orders per customer
WITH r AS (
  SELECT o.*, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC, id) AS rn
  FROM orders o
)
SELECT * FROM r WHERE rn <= 3;

Conviene saberlo

  • The filter must live outside the window: WHERE rn <= N in the same SELECT is invalid because windows evaluate after WHERE. A CTE or derived table is the portable wrapper.
  • Ties beyond N are silently dropped and, without a unique tiebreaker, which rows make the cut can change run to run. Append a unique column as the last ORDER BY key.
  • For 'N including ties' use RANK or DENSE_RANK instead: RANK() <= 3 can return four rows when two tie for third.

Questions about Top N Per Group

Why is there no LIMIT per group in SQL?

LIMIT applies to the whole result set, not per partition. The portable fix is exactly this pattern: number rows per partition, then filter. PostgreSQL also offers DISTINCT ON for N = 1.

ROW_NUMBER, RANK or DENSE_RANK for top N?

ROW_NUMBER for exactly N rows, RANK for N including ties (can exceed N), DENSE_RANK when ties should share a level and the count of levels is what matters.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.