Advanced · Lesson 3 of 18

PARTITION BY

PARTITION BY divides rows into groups for separate calculations.

Rank within each department:

SELECT department_id, first_name, salary,
       RANK() OVER (
           PARTITION BY department_id
           ORDER BY salary DESC
       ) as dept_rank
FROM employees;

Each department gets its own ranking (1, 2, 3...).

This is the "Top N per group" pattern - extremely common!

Check your understanding

Rank employees by salary within their department (top earner = 1).

Examples run on the employees sample database. Open any of them in the playground to experiment.