SQL ROW_NUMBER(): How to Number Rows
By Sharon Ben-Moshe · August 26, 2026 · 2 min read
Sharon Ben-Moshe is the founder of sqlfmt, a browser-based SQL formatter and validator with misspelled-keyword suggestions across PostgreSQL, MySQL, SQLite, SQL Server, and BigQuery.
Learn SQL ROW_NUMBER with practical examples for numbering rows, latest-row-per-group queries, tie-breaking, and when RANK is the better choice.
Quick answer
ROW_NUMBER() assigns a sequential number to each row within an ordered window, restarting for every PARTITION BY group. Add a deterministic tie-breaker to ORDER BY, then filter row_number = 1 in an outer query to keep one latest row per group.
FAQs
Does ROW_NUMBER restart for each group?
Yes, when PARTITION BY is present. ROW_NUMBER starts at 1 for each partition. Without PARTITION BY, it numbers the entire result set according to the ORDER BY inside the OVER clause.
Why does ROW_NUMBER give different results for ties?
If the window ORDER BY values tie, the database has no complete ordering between those peer rows. Add a stable, unique tie-breaker such as a primary key when one row must consistently receive row number 1.
Can I use ROW_NUMBER in WHERE?
Not directly in the same query level’s WHERE clause because window functions are evaluated later. Compute ROW_NUMBER in a CTE, subquery, or a dialect feature such as BigQuery QUALIFY, then filter the resulting row number.
What is the difference between ROW_NUMBER and RANK?
ROW_NUMBER gives every row a distinct sequential number. RANK gives equal ORDER BY values the same rank and leaves gaps after ties. DENSE_RANK gives ties the same rank without gaps.
Keep reading
SQL COALESCE vs ISNULL: Key Differences
By Sharon Ben-Moshe · Aug 26, 2026
Compare SQL COALESCE and ISNULL: argument count, portability, return types, nullability, evaluation behavior, and the MySQL naming trap.
Read postSQL Date Difference: DATEDIFF by Database
By Sharon Ben-Moshe · Aug 26, 2026
Calculate date differences in SQL Server, MySQL, PostgreSQL, SQLite, and BigQuery. Learn syntax, argument order, timestamp behavior, and boundary rules.
Read postTry it now
Paste your SQL into sqlfmt — format, validate, and catch typos free in your browser.