SQL Window Functions Explained: ROW_NUMBER, RANK and More
SQL window functions add a calculated value to every row without collapsing rows like GROUP BY. See ROW_NUMBER, RANK and DENSE_RANK side by side with real result rows.
Short answer: SQL window functions calculate a value for each row from a set of related rows, called a window, without collapsing those rows into one the way GROUP BY does. You write them with an OVER clause, for example ROW_NUMBER() OVER (PARTITION BY class ORDER BY score DESC), to number, rank or compare rows.
How do SQL window functions differ from GROUP BY?
SQL window functions keep every row, while GROUP BY returns one row per group. With GROUP BY you can get the average score of each class; with a window function you can show every student and their class average on the same line. If GROUP BY and HAVING are still fuzzy, read WHERE vs GROUP BY vs HAVING first.
GROUP BY | Window function | |
|---|---|---|
Rows returned | One per group | Every input row |
Typical question | What is each class's average? | Where does each student rank in their class? |
Can see individual rows | No, only aggregates | Yes, next to the calculated value |
Syntax | GROUP BY column | function() OVER (...) |
What does the OVER clause do?
The OVER clause defines the window that a window function looks at. It has up to three parts:
PARTITION BY splits rows into groups, such as one group per class. Without it, the whole result is one window.
ORDER BY sets the order inside each partition, which ranking functions need.
A frame (such as ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) limits the window to nearby rows for running totals and moving averages.
What is the difference between ROW_NUMBER, RANK and DENSE_RANK?
ROW_NUMBER, RANK and DENSE_RANK all number rows in order, but they treat ties differently. To see it, create this small table. All the SQL in this post runs unchanged in PostgreSQL and SQLite.
CREATE TABLE scores (name TEXT, class TEXT, score INTEGER);
INSERT INTO scores (name, class, score) VALUES
('Ana', 'A', 90), ('Ben', 'A', 85), ('Chen', 'A', 90), ('Dev', 'A', 70),
('Eli', 'B', 88), ('Fay', 'B', 95), ('Gus', 'B', 88);Now rank class A, where Ana and Chen tie on 90:
SELECT name, score,
ROW_NUMBER() OVER (ORDER BY score DESC, name) AS row_num,
RANK() OVER (ORDER BY score DESC) AS rnk,
DENSE_RANK() OVER (ORDER BY score DESC) AS dense_rnk
FROM scores
WHERE class = 'A'
ORDER BY score DESC, name;The result:
name | score | row_num | rnk | dense_rnk |
|---|---|---|---|---|
Ana | 90 | 1 | 1 | 1 |
Chen | 90 | 2 | 1 | 1 |
Ben | 85 | 3 | 3 | 2 |
Dev | 70 | 4 | 4 | 3 |
ROW_NUMBER gives every row a unique number, even for ties. The extra
namein its ORDER BY decides who comes first; without a tie-breaker the order between Ana and Chen is not guaranteed.RANK gives ties the same number, then skips: two people share 1, so the next is 3.
DENSE_RANK gives ties the same number without gaps: the next is 2.
A simple rule: use ROW_NUMBER when you need exactly one row per position, RANK for sports-style rankings, and DENSE_RANK when you want the "second highest value" regardless of ties.
How do you get the top row in each group?
To get the top scorer in each class, number the rows per class with PARTITION BY and keep row number 1. You cannot use a window function in WHERE directly, so wrap it in a subquery:
SELECT name, class, score
FROM (
SELECT name, class, score,
ROW_NUMBER() OVER (PARTITION BY class ORDER BY score DESC, name) AS rn
FROM scores
) AS ranked
WHERE rn = 1
ORDER BY class;name | class | score |
|---|---|---|
Ana | A | 90 |
Fay | B | 95 |
This "top N per group" pattern is one of the most common reasons people learn window functions.
Can window functions use aggregates like MAX and SUM?
Yes. Any aggregate such as SUM, AVG, MIN or MAX becomes a window function when you add OVER. This query shows how far each student is from the best score in their class:
SELECT name, class, score,
score - MAX(score) OVER (PARTITION BY class) AS gap_to_best
FROM scores
ORDER BY class, name;name | class | score | gap_to_best |
|---|---|---|---|
Ana | A | 90 | 0 |
Ben | A | 85 | -5 |
Chen | A | 90 | 0 |
Dev | A | 70 | -20 |
Eli | B | 88 | -7 |
Fay | B | 95 | 0 |
Gus | B | 88 | -7 |
Other useful window functions are LAG and LEAD (the previous or next row's value) and SUM() OVER (ORDER BY ...) for running totals. The free chapters Window Functions I and Window Functions II practise them step by step, and the official PostgreSQL window functions tutorial is a good reference.
Common mistakes
Filtering on a window function in WHERE. WHERE runs before window functions are calculated; use a subquery or CTE.
Using ROW_NUMBER without a unique tie-breaker, so results change between runs.
Using RANK for "top 3" and getting four rows because of a tie (or the reverse with ROW_NUMBER).
Forgetting PARTITION BY, so the ranking runs across the whole table instead of per group.
Frequently Asked Questions
Can you use a window function in a WHERE clause?
No. Window functions are calculated after WHERE, GROUP BY and HAVING, so you compute them in a subquery or CTE and filter in the outer query.
What is the difference between PARTITION BY and GROUP BY?
PARTITION BY divides rows into groups for a window function but keeps every row in the result. GROUP BY merges each group into a single output row.
Which databases support SQL window functions?
Current versions of PostgreSQL, MySQL, SQLite, SQL Server and Oracle all support window functions. Very old versions may not, so check your version's documentation if a query fails.
Are window functions asked in SQL interviews?
Yes, window functions are a common topic in data and analyst interviews, especially the difference between ROW_NUMBER, RANK and DENSE_RANK and the top-N-per-group pattern. See these SQL interview questions for freshers to practise.
Key Takeaway
Window functions add a calculated value to every row using OVER, without collapsing rows like GROUP BY. Learn ROW_NUMBER, RANK and DENSE_RANK through how they handle ties, then use PARTITION BY for per-group results.
Ready to start? You will practise window functions, CTEs and other advanced SQL on realistic data for AI projects. Begin with the free course SQL and Data Handling for AI: Advanced.
Related articles
More in SQL and Data
SQL vs Excel: When to Use Each
A clear comparison of SQL and Excel: what each is good at, the same task done in both, and how to decide which to use or how to combine them.
4 min readNov 24, 2026NULL in SQL: 5 Common Mistakes and Fixes
NULL means unknown, not zero. Learn the five SQL NULL mistakes beginners make, from = NULL to NOT IN, and the exact fix for each, with a table you can run yourself.
5 min readNov 21, 2026SQL JOINs Explained With Examples
INNER, LEFT, RIGHT and FULL JOIN explained with two tiny tables, the exact results of each query, how to find unmatched rows, and the mistakes that trip people up.
4 min readNov 18, 2026SQL vs Python for Data Analysis
SQL and Python do different jobs in data analysis. See what each is best at, a side-by-side example, and which one to learn first.
4 min readNov 15, 2026Primary Key vs Foreign Key in SQL
What primary and foreign keys are, how they differ, and how a runnable customers-and-orders example shows the database enforcing them.
4 min readNov 13, 2026WHERE vs GROUP BY vs HAVING in SQL
WHERE filters rows, GROUP BY builds groups and HAVING filters groups. See one worked example, the order SQL runs them in, and the mistakes to avoid.
3 min readNov 10, 2026
Comments
Sign in to join the discussion.

