Example 1
Rank employees by salary within each department
PARTITION BY department restarts the counter for each department. ORDER BY salary DESC determines which employee gets rank 1 (the highest earner). Each department's numbering is independent — both Ada and Karen receive row_num 1 within their respective groups.
CREATE TABLE employees (
id INT,
name VARCHAR(50),
department VARCHAR(50),
salary INT
);
INSERT INTO
employees (id, name, department, salary)
VALUES
(1, 'Ada', 'Engineering', 90000),
(2, 'Grace', 'Engineering', 85000),
(3, 'Linus', 'Engineering', 80000),
(4, 'Karen', 'Finance', 75000),
(5, 'Steve', 'Finance', 70000);SELECT
name,
department,
salary,
ROW_NUMBER() OVER (
PARTITION BY
department
ORDER BY
salary DESC
) AS row_num
FROM
employees
ORDER BY
department,
row_num;| name | department | salary | row_num |
|---|---|---|---|
| Ada | Engineering | 90000 | 1 |
| Grace | Engineering | 85000 | 2 |
| Linus | Engineering | 80000 | 3 |
| Karen | Finance | 75000 | 1 |
| Steve | Finance | 70000 | 2 |
Output is identical across all supported engine versions.