SQL window functions: PARTITION BY, ROW_NUMBER and RANK
Window functions calculate across a set of rows without collapsing them into one. Use them to number products by price, rank results with ties or pick the two priciest products in each category, while every row stays in the result.
In short: ROW_NUMBER() OVER (ORDER BY price DESC) numbers rows in the order you give it. Add PARTITION BY category inside OVER and the count restarts at 1 for every category. RANK() and DENSE_RANK() give tied values the same rank. A window function can't go in WHERE; to filter on it, put it in a CTE first.
What you should know first: sorting with ORDER BY, grouping with GROUP BY and building steps with WITH (CTE).
Try it now
The first window function is also the simplest: ROW_NUMBER() counts 1, 2, 3 in whatever order you set inside OVER. All twelve products stay in the result; you just get one extra column.
Task For the new catalog, number the products by price, with the most expensive one as number 1. Show name, price and rank_no for every product. Work out the number with ROW_NUMBER().
products 12 rows, 5 columns
| product_id | name | category | price | stock |
|---|---|---|---|---|
| 1 | Copy paper, 500 sheets | Paper | 4.99 | 420 |
| 2 | Blue ballpoint pens, 10-pack | Writing | 3.49 | 310 |
| 3 | Lever arch file, gray | Filing | 2.79 | 185 |
| 4 | Comfort office chair | Furniture | 189 | 12 |
| 5 | Standing desk | Furniture | 449 | 5 |
| 6 | Black ink cartridge | Printer supplies | 24.9 | 64 |
| 7 | Yellow sticky notes, 12 pads | Writing | 6.99 | 0 |
| 8 | Mono laser printer L30 | Electronics | 219 | 8 |
| 9 | 27-inch monitor | Electronics | 279 | 15 |
| 10 | Notebook A5, ruled | Paper | 5.49 | 140 |
| 11 | Black toner XL | Printer supplies | 89.9 | 22 |
| 12 | Cross-cut shredder | Electronics | 129 | 0 |
How window functions work
You can spot a window function by the keyword OVER. The brackets after it describe the "window": which rows belong together (PARTITION BY) and in what order they're looked at (ORDER BY). The difference from GROUP BY is easiest to see side by side. GROUP BY collapses rows, so ten employees turn into five departments:
SELECT department, COUNT(*) AS headcount
FROM employees
GROUP BY department;
A window function keeps all ten rows and adds where each person stands within their department:
SELECT first_name, department, salary,
ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn
FROM employees;
| first_name | department | salary | rn |
|---|---|---|---|
| Nina | Accounting | 52800 | 1 |
| Paul | Accounting | 43200 | 2 |
| David | Customer service | 38400 | 1 |
| Laura | Customer service | NULL | 2 |
| Karen | Management | 93600 | 1 |
| Tom | Sales | 62400 | 1 |
| Marcus | Sales | 49200 | 2 |
| Julia | Sales | 46800 | 3 |
| Sarah | Warehouse | 39600 | 1 |
| Felix | Warehouse | 35400 | 2 |
PARTITION BY department splits the table into five groups and the count starts over at 1 in each. Laura Hughes has no salary yet and comes second in Customer service, because SQLite puts NULL last when sorting in descending order. The rows happen to come out grouped by department, but don't rely on it; add your own ORDER BY at the end if order matters.
ROW_NUMBER vs RANK vs DENSE_RANK with ties
As long as no value repeats, all three return the same numbers. Ties are where they part ways. How many orders has each customer placed, and where do they rank? A CTE counts the orders, then three functions hand out their numbers:
WITH order_counts AS (
SELECT c.name, COUNT(*) AS orders
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id
)
SELECT name, orders,
ROW_NUMBER() OVER (ORDER BY orders DESC, name) AS row_no,
RANK() OVER (ORDER BY orders DESC) AS rnk,
DENSE_RANK() OVER (ORDER BY orders DESC) AS dense_rnk
FROM order_counts
ORDER BY orders DESC, name;
The first seven of twelve rows:
| name | orders | row_no | rnk | dense_rnk |
|---|---|---|---|---|
| Harbor Fremont Partners | 3 | 1 | 1 | 1 |
| Greene & Shaw LLP | 2 | 2 | 2 | 2 |
| Northline Printing Co | 2 | 3 | 2 | 2 |
| Raj Patel | 2 | 4 | 2 | 2 |
| Riverside County Office | 2 | 5 | 2 | 2 |
| Chloe Evans | 1 | 6 | 6 | 3 |
| Daniel Kim | 1 | 7 | 6 | 3 |
- ROW_NUMBER keeps counting no matter what. Among tied rows, only a second sort column (the name here) decides who comes first; without one the order isn't defined.
- RANK gives ties the same rank and then skips as many numbers as there were tied rows: four customers share rank 2, the next one is rank 6.
- DENSE_RANK also gives ties the same rank, but carries on without a gap: after 2 comes 3. Handy when the question is "the second-highest value".
Task Purchasing wants to see which products are running lowest: smallest stock first. Show name, stock, place and tier. place works like a sports ranking: same stock, same place, and the next numbers are skipped. tier also gives equal stock the same number, but leaves no gap afterwards.
products 12 rows, 5 columns
| product_id | name | category | price | stock |
|---|---|---|---|---|
| 1 | Copy paper, 500 sheets | Paper | 4.99 | 420 |
| 2 | Blue ballpoint pens, 10-pack | Writing | 3.49 | 310 |
| 3 | Lever arch file, gray | Filing | 2.79 | 185 |
| 4 | Comfort office chair | Furniture | 189 | 12 |
| 5 | Standing desk | Furniture | 449 | 5 |
| 6 | Black ink cartridge | Printer supplies | 24.9 | 64 |
| 7 | Yellow sticky notes, 12 pads | Writing | 6.99 | 0 |
| 8 | Mono laser printer L30 | Electronics | 219 | 8 |
| 9 | 27-inch monitor | Electronics | 279 | 15 |
| 10 | Notebook A5, ruled | Paper | 5.49 | 140 |
| 11 | Black toner XL | Printer supplies | 89.9 | 22 |
| 12 | Cross-cut shredder | Electronics | 129 | 0 |
This exercise is part of Premium.
Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.
See Premium Already Premium? Log in
The first exercise in this lesson is free.
Top N per group
The most common office job for window functions is the newest, biggest or priciest item in each group. The obvious attempt, WHERE ROW_NUMBER() OVER (…) <= 2, fails, because window functions are calculated only after WHERE has picked the rows. So you work in two steps: a CTE numbers the rows, and the query after it filters. Here is the latest order for each customer:
WITH ranked AS (
SELECT customer_id, order_id, order_date,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC) AS rn
FROM orders
)
SELECT customer_id, order_id, order_date
FROM ranked
WHERE rn = 1
ORDER BY customer_id;
The first four of twelve rows, one per customer:
| customer_id | order_id | order_date |
|---|---|---|
| 1 | 1015 | 2026-06-10 |
| 2 | 1005 | 2026-02-11 |
| 3 | 1012 | 2026-05-06 |
| 4 | 1017 | 2026-06-13 |
Harbor Fremont Partners (customer 1) has three orders, and only the one from 10 June is left. For the two most recent, write rn <= 2. If tied rows should all make the cut, use RANK instead of ROW_NUMBER.
Task The shop's home page should feature the two most expensive products in each category. Show category, name and price for those products. A category with only one product appears with that one.
products 12 rows, 5 columns
| product_id | name | category | price | stock |
|---|---|---|---|---|
| 1 | Copy paper, 500 sheets | Paper | 4.99 | 420 |
| 2 | Blue ballpoint pens, 10-pack | Writing | 3.49 | 310 |
| 3 | Lever arch file, gray | Filing | 2.79 | 185 |
| 4 | Comfort office chair | Furniture | 189 | 12 |
| 5 | Standing desk | Furniture | 449 | 5 |
| 6 | Black ink cartridge | Printer supplies | 24.9 | 64 |
| 7 | Yellow sticky notes, 12 pads | Writing | 6.99 | 0 |
| 8 | Mono laser printer L30 | Electronics | 219 | 8 |
| 9 | 27-inch monitor | Electronics | 279 | 15 |
| 10 | Notebook A5, ruled | Paper | 5.49 | 140 |
| 11 | Black toner XL | Printer supplies | 89.9 | 22 |
| 12 | Cross-cut shredder | Electronics | 129 | 0 |
This exercise is part of Premium.
Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.
See Premium Already Premium? Log in
The first exercise in this lesson is free.
Common mistakes
A window function in WHERE
Neither WHERE ROW_NUMBER() OVER (…) <= 2 nor WHERE rn <= 2 with the alias from the same SELECT works. The exercise then tells you that window functions can't go in WHERE, because they are computed after it. The fix is to number the rows in a CTE first and filter afterwards.
Forgetting OVER
ROW_NUMBER() AS rn without OVER isn't a complete window function. The exercise shows the same message as for the mistake above, and here its last sentence is the one that matters: every window function needs OVER (…), even if the brackets are empty.
A comma between PARTITION BY and ORDER BY
Inside OVER, PARTITION BY and ORDER BY follow each other without a comma: OVER (PARTITION BY category ORDER BY price DESC). With a comma the exercise reports a syntax error near "ORDER".
Leaving out PARTITION BY
Without PARTITION BY, ROW_NUMBER counts across the whole table. For a top N per group you then only get the first rows overall, and the exercise tells you your result has too few rows.
Mixing up RANK and DENSE_RANK
Both give ties the same number; they only differ after the tie. Swap them and each column holds the other one's values, and that is exactly what the exercise reports.
Window functions in MySQL, PostgreSQL, SQL Server and SQLite
ROW_NUMBER, RANK, DENSE_RANK, OVER and PARTITION BY are written the same way in all four. The differences are in versions and what's required:
| Database | Available | ORDER BY inside OVER |
|---|---|---|
| MySQL | from 8.0 | optional; without it ROW_NUMBER's numbering isn't defined, and RANK and DENSE_RANK give every row the same rank |
| PostgreSQL | yes | decides the counting order and which rows count as tied |
| SQL Server | yes | required for ROW_NUMBER, RANK and DENSE_RANK |
| SQLite (these exercises) | from 3.25.0 (September 2018) | optional |
The MySQL, PostgreSQL and SQLite docs all say window functions are allowed only in the SELECT list and in ORDER BY, because they run after WHERE, GROUP BY and HAVING. To filter on a row number there, you need a CTE or subquery. For SQL Server, Microsoft points out that ROW_NUMBER only returns the same numbers on every run when the sort order is unique. The same advice holds everywhere: with ties, add a second sort column such as the ID inside OVER.
Sources: MySQL Reference Manual (What Is New in MySQL 8.0, Window Function Concepts and Syntax, Window Function Descriptions), PostgreSQL documentation (Window Functions tutorial and function list), Microsoft Learn (ROW_NUMBER, RANK, DENSE_RANK), sqlite.org (Window Functions).
FAQ
What's the difference between a window function and GROUP BY?
GROUP BY folds rows into one row per group, and details such as names are lost. A window function leaves every row in place and adds the result of its calculation. You see each row and its position in the group at the same time.
How do I find the second-highest salary?
Use DENSE_RANK in a CTE: WITH r AS (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk FROM employees) SELECT DISTINCT salary FROM r WHERE rnk = 2. DENSE_RANK fits better than RANK here, because two equal top salaries would otherwise make rank 2 disappear.
Does the ORDER BY inside OVER sort my result?
No. It only sets the order in which the function counts. The output order is set only by the ORDER BY at the end of the query.
Can I use several window functions in one query?
Yes, as many as you need, each with its own OVER. The second exercise puts RANK and DENSE_RANK side by side, and the example above uses three.