SQL ROW_NUMBER function
Numbers rows 1, 2, 3... within a partition, ordered as specified. No gaps, no ties, which is exactly what deduplication and top-N-per-group need.
- 类别
- 窗口
- Returns
bigint- In this category
- 1 of 79
语法
ROW_NUMBER() OVER (PARTITION BY g ORDER BY x)
引擎支持
| 引擎 | 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
SELECT customer_id, amount,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC) AS rn
FROM orders;
Any engine
-- top order per customer WITH ranked AS ( SELECT o.*, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC, id) AS rn FROM orders o ) SELECT * FROM ranked WHERE rn = 1;
值得了解
- Without a full tiebreaker in ORDER BY, equal rows can number differently run to run; nondeterministic dedupes are the classic production bug. Add a unique column as the final ORDER BY key.
- Window functions cannot appear in WHERE: wrap the query in a CTE or subquery and filter on rn = 1 outside.
- ROW_NUMBER vs RANK: ROW_NUMBER never ties; RANK gives tied rows the same number and skips the next ones.
Questions about ROW_NUMBER
How do I get the latest row per group?
ROW_NUMBER() OVER (PARTITION BY group ORDER BY updated_at DESC, id) in a CTE, then filter WHERE rn = 1. The id tiebreaker makes it deterministic.
Why can't I use ROW_NUMBER in WHERE?
Window functions evaluate after WHERE. Put them in a subquery or CTE and filter on the computed number outside.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
- Numbering rows: ROW_NUMBER, ROWNUM and rowid Dialect comparison
- First N rows per group: ROW_NUMBER vs DISTINCT ON Dialect comparison
- Dedupe with window functions Snippet
- Deduplicate SELECT output Snippet
- Delete duplicates keeping one row 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.