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
The Comprehensive Guide to SQL Data Types: Storage, Precision, and Cross-Dialect Portability
By Sharon Ben-Moshe · Oct 13, 2026
The complete guide to SQL data types across PostgreSQL, MySQL, SQL Server, and SQLite. Numeric precision, character sets, timestamps, and JSON.
Read postThe Definitive Guide to SQL Window Functions: Syntax, Framing, and Real-World Recipes
By Sharon Ben-Moshe · Oct 13, 2026
The comprehensive guide to SQL window functions. Master OVER, PARTITION BY, ORDER BY, window frames (ROWS vs RANGE), and ranking recipes.
Read postTry it now
Paste your SQL into sqlfmt — format, validate, and catch typos free in your browser.