Combined review · case study

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.

30–35 minIntermediate levelFirst you need: CASE, ORDER BY and window functions

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

Not started

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.

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 CASE and ROW_NUMBER in the same result.
  • Recognise why the ordering inside OVER must 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

NeedToolFinal rows
Assign a label based on the rowCASEOne per input row
Summarise a departmentGROUP BY and aggregatesOne per group
Compare or number within the departmentWindow functionEvery 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.

SQL
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;
Result fragment
namedepartmentsalarybandposition
Graham NewtonMarketing31500initial band1
Helen CooperMarketing30000initial band2
Charles PageTechnology46000high band1
Diana LaneTechnology39000high band2
Isaac DavisSales36000high band1
Alex ReedSales33000initial band2
Beth MorganSales28000initial band3
  1. PARTITION BY department restarts the numbering in each department.
  2. ORDER BY salary DESC, id decides which row gets each position.
  3. CASE calculates a separate label for the current row.
  4. The ORDER BY at 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.

SQL · SQLite
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;
The nine result rows
namedepartmentsalarybandposition
Claire SmithManagement52000high band1
Graham NewtonMarketing31500initial band1
Helen CooperMarketing30000initial band2
Faith RiversSupport29500initial band1
Ernest ColeSupport27000initial band2
Charles PageTechnology46000high band1
Diana LaneTechnology39000high band2
Isaac DavisSales36000high band1
Alex ReedSales33000initial band2

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

  • CASE returns a value based on conditions.
  • Window functions calculate over related rows without collapsing them.
  • To filter a window result, use a subquery or CTE.

Suggested path