ROW_NUMBER is a window (analytic) function defined in the SQL:2003 standard. It scans the rows returned by a query, groups them into optional partitions, orders each partition by the given columns, and then labels the rows 1, 2, 3, … in that order. The numbering restarts for every partition. Because the numbering is deterministic when ORDER BY is unambiguous, ROW_NUMBER is ideal for pagination, top-N reports, de-duplicating identical rows, or building deterministic surrogate keys in result sets. Unlike RANK and DENSE_RANK, ROW_NUMBER never produces gaps because each row receives exactly one distinct integer. If ORDER BY is omitted (only valid in some dialects) the numbering order is implementation-dependent, so always specify ORDER BY for predictable output. ROW_NUMBER is evaluated after WHERE, GROUP BY, and HAVING but before the final ORDER BY of the SELECT statement. It cannot be used in WHERE directly; wrap the query in a subquery or common table expression (CTE) and filter on the derived column.
PARTITION BY
(expression) - Divides the result set into independent groups before numbering.ORDER BY
(expression) - Defines the sort order inside each partition and therefore the numbering sequence.ASC
(DESC) - keyword|||Sort direction (default ASC).SQL:2003
It returns an integer starting at 1 for the first row in each ordered partition and increases by 1 for every subsequent row.
Wrap the query in a CTE, compute ROW_NUMBER partitioned by the group column and ordered by your preference, then filter WHERE row_num = 1.
Performance is usually identical because all three are evaluated in the same window-function phase. Choose based on the numbering semantics you need, not speed.
Yes. If PARTITION BY is omitted the function treats the entire result set as a single partition and numbers all rows globally.