ROW_NUMBER() adds a sequential integer to rows in the result set based on the ORDER BY clause within an OVER() window.
ROW_NUMBER() creates a temporary, query-level sequence without altering tables. Use it for ranking, pagination, and deduplication when you cannot—or should not—add a physical column.
ROW_NUMBER() operates as a window function: ROW_NUMBER() OVER (ORDER BY column_list)
. The ORDER BY inside OVER() determines row numbering, independent of the query’s outer ORDER BY.
Assign numbers, then filter: WITH ordered AS (SELECT ROW_NUMBER() OVER (ORDER BY order_date DESC) AS rn, * FROM Orders) SELECT * FROM ordered WHERE rn BETWEEN 11 AND 20;
This returns page 2 (rows 11-20) of recent orders.
Rank duplicates, keep the first: WITH dup AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY email ORDER BY created_at) AS rn FROM Customers) DELETE FROM dup WHERE rn > 1;
Only the earliest sign-up per email remains.
Yes. PARTITION BY resets numbering per group while ORDER BY defines order inside each group. Example: number orders per customer.
SELECT customer_id,
order_date,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date) AS order_seq
FROM Orders;
Create indexes that support the ORDER BY columns. Avoid functions or expressions that disable index usage. Keep the window frame simple.
1. Omitting ORDER BY inside OVER(). Without it, numbering order is undefined. 2. Filtering on the same rowset before numbering. Always generate ROW_NUMBER() first, then filter by the generated alias in an outer query or CTE.
Use ROW_NUMBER() for ranking, pagination, and deduplication. Combine with PARTITION BY for per-group sequences. Always specify ORDER BY, and filter in an outer query for predictable results.
No, but duplicate sort values lead to non-deterministic numbering. Add tiebreaker columns for consistent results.
No. Use a subquery or CTE because window function aliases are computed after the SELECT list.
For read-only queries, ROW_NUMBER() is efficient. IDENTITY is faster for permanent sequencing but requires schema changes.