CASE and ROW_NUMBER in SQL: a ranking-per-group exercise
Create a category for each row and calculate its position within a group, without reducing the result to one row per group.
Have a go before opening the examples
First you need: Create categories with CASE, Number rows with ROW_NUMBER, Break queries into steps with CTEs. If any of the groundwork is missing, go back to that lesson and then carry on from here.
Complete each task, predict a row and explain the decision that produces it. Results are saved per activity.
Practice
Classify and choose a position
Use a CTE that classifies employees as 'high' if salary >= 30000, or 'entry' otherwise, with the alias band. Number them per department by salary DESC and id ASC. Return name, department and band for position 1, sorted by department.
Expected result: 5 rows with the columns name, department, band, in that order. Keep the row order requested.
View tables and data
Open this panel to see the full data.
Separating the label from the position helps clarify what each expression calculates.
Filter on position in an outer query.
id breaks salary ties inside OVER.
Solution explained
WITH ranking AS (SELECT name,department,CASE WHEN salary >= 30000 THEN 'high' ELSE 'entry' END AS band,ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC,id) AS position FROM employees) SELECT name,department,band FROM ranking WHERE position = 1 ORDER BY department;CASE classifies each row; ROW_NUMBER assigns its position; the outer query filters on that position without changing the set that went into the window.
To finish: explain what a row represents, which requirement you checked and what would change if the rule changed.
See worked examples and checks
By the end, you will be able to
- Tell apart a conditional calculation from a calculation over related rows.
- Combine
CASEandROW_NUMBERin the same result. - Recognise why the ordering inside
OVERmust be deterministic.
Two tools that answer different questions
CASE evaluates conditions and returns a value. A window function uses a set of rows related to the current row. Both keep the detail: they do not collapse several rows into one, the way an ordinary aggregate does with GROUP BY.
Mental model: CASE asks «which label belongs to this row?». ROW_NUMBER() OVER (...) asks «what position does this row hold within its partition and ordering?».
Choose the tool by the shape of the result
| Need | Tool | Final rows |
|---|---|---|
| Assign a label based on the row | CASE | One per input row |
| Summarise a department | GROUP BY and aggregates | One per group |
| Compare or number within the department | Window function | Every employee is kept |
This comparison avoids a common mistake: using a window when you really want a summary, or grouping when you still need to see each employee's detail.
Verified example
We classify the salary and calculate a position within each department. The second ordering criterion, id, breaks ties in a stable way.
SELECT name,
department,
salary,
CASE
WHEN salary >= 35000 THEN 'high band'
ELSE 'initial band'
END AS band,
ROW_NUMBER() OVER (
PARTITION BY department
ORDER BY salary DESC, id
) AS position
FROM employees
ORDER BY department, position;| name | department | salary | band | position |
|---|---|---|---|---|
| Graham Newton | Marketing | 31500 | initial band | 1 |
| Helen Cooper | Marketing | 30000 | initial band | 2 |
| Charles Page | Technology | 46000 | high band | 1 |
| Diana Lane | Technology | 39000 | high band | 2 |
| Isaac Davis | Sales | 36000 | high band | 1 |
| Alex Reed | Sales | 33000 | initial band | 2 |
| Beth Morgan | Sales | 28000 | initial band | 3 |
PARTITION BY departmentrestarts the numbering in each department.ORDER BY salary DESC, iddecides which row gets each position.CASEcalculates a separate label for the current row.- The
ORDER BYat the outer level organises the visible result; it does not replace the window's ordering.
The window's ordering must break ties
ROW_NUMBER() always assigns different numbers, even to rows with the same salary. If the window's ORDER BY does not decide which one comes first, the engine may number them in an unspecified order. Adding id as a second criterion makes the result reproducible.
Semantic decision: uses ROW_NUMBER when you need a unique sequence. If tied rows should share a position, look at RANK or DENSE_RANK; do not switch functions just to get a different-looking numbering.
Why you need an outer query
Window functions are calculated after WHERE, GROUP BY and HAVING. That's why the alias position does not exist yet when the WHERE at the same level is processed. The CTE creates an intermediate result, which the outer query can then filter.
Worked exercise: two employees per department
Use the same employees table as in the previous example. First calculate the salary band and the ranking for every employee; then keep positions 1 and 2. You can reproduce it in SQLite with the StoreSQL database.
WITH ranked AS (
SELECT id, name, department, salary,
CASE WHEN salary >= 35000 THEN 'high band'
ELSE 'initial band' END AS band,
ROW_NUMBER() OVER (
PARTITION BY department
ORDER BY salary DESC, id
) AS position
FROM employees
)
SELECT name, department, salary, band, position
FROM ranked
WHERE position <= 2
ORDER BY department, position;| name | department | salary | band | position |
|---|---|---|---|---|
| Claire Smith | Management | 52000 | high band | 1 |
| Graham Newton | Marketing | 31500 | initial band | 1 |
| Helen Cooper | Marketing | 30000 | initial band | 2 |
| Faith Rivers | Support | 29500 | initial band | 1 |
| Ernest Cole | Support | 27000 | initial band | 2 |
| Charles Page | Technology | 46000 | high band | 1 |
| Diana Lane | Technology | 39000 | high band | 2 |
| Isaac Davis | Sales | 36000 | high band | 1 |
| Alex Reed | Sales | 33000 | initial band | 2 |
Management has only one person: the query does not make up a second row. Beth Morgan is left out because she is third in Sales. The CASE labels the rows; the outer WHERE decides which ones are shown.
Filter before or after ranking?
If you put WHERE salary < 35000 inside the CTE, you number only the people who meet that condition: in Sales, Alex and Beth Morgan would appear. If you add that filter in the outer query together with position <= 2, you rank everyone first and then keep only Alex. They are different questions and can return different numbers of rows.
To go further into the choice between keeping ties and picking a fixed number of rows, see Top N per group; to understand the stages, see the logical order of a SQL query.
Common mistake: trying to filter the window in WHERE
The position does not exist yet at that logical point
SELECT name,
ROW_NUMBER() OVER (ORDER BY salary DESC) AS position
FROM employees
WHERE position <= 3;Window functions are calculated after WHERE. To filter by position, first compute the window in a subquery or CTE and filter on the outer query.
Check what you have mastered
- You can tell apart a label per row, a summary per group and a window calculation.
- You include a tiebreaker when you need reproducible positions.
- You can explain why a CTE or subquery lets you filter the result of
ROW_NUMBER. - You do not promise two rows when a partition contains only one.
Key takeaways
CASEreturns a value based on conditions.- Window functions calculate over related rows without collapsing them.
- To filter a window result, use a subquery or CTE.