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'.
- 類別
- 視窗
- Returns
N rows per group- In this category
- 28 of 79
語法
WITH r AS (SELECT ..., ROW_NUMBER() OVER (PARTITION BY g ORDER BY x DESC) AS rn FROM t) SELECT * FROM r WHERE rn <= N
引擎支援
| 引擎 | Support | 備註 |
|---|---|---|
| SQL Server | 是 | Supported under this name. |
| PostgreSQL | 是 | Supported under this name. |
| MySQL | 是 | MySQL 8.0+ |
| SQLite | 是 | SQLite 3.25+ |
| Oracle | 是 | Supported under this name. |
範例
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;
小知識
- 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.
Related on SQLly
- First N rows per group: ROW_NUMBER vs DISTINCT ON Dialect comparison
- Top-N rows per group Snippet
- SQL window function interview questions Interview questions
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
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.