CTEs and Window Functions · Lesson 20 of 30
SQL Window Functions: ROW_NUMBER, RANK, DENSE_RANK
GROUP BY collapses rows into one per group. Window functions calculate across a group of rows without collapsing them – each row keeps its details and gains a value like its rank, the group average, or a running total. They solve "top 3 per department", "second highest salary" and "compare with the previous month" elegantly, and they're among the most-asked topics in SQL interviews.
In this lesson
- The
OVER()clause andPARTITION BY - Aggregates as window functions
ROW_NUMBERvsRANKvsDENSE_RANK- Top N per group and the Nth highest value
OVER(): aggregates without collapsing
SELECT name,
department,
salary,
ROUND(AVG(salary) OVER ()) AS company_avg,
ROUND(AVG(salary) OVER (PARTITION BY department)) AS dept_avg,
salary - ROUND(AVG(salary) OVER (PARTITION BY department)) AS vs_dept
FROM employees
ORDER BY department, salary DESC, name;
+--------------+-------------+--------+-------------+----------+---------+ | name | department | salary | company_avg | dept_avg | vs_dept | +--------------+-------------+--------+-------------+----------+---------+ | Rohit Mehta | Engineering | 180000 | 122300 | 128750 | 51250 | | Dev Patel | Engineering | 120000 | 122300 | 128750 | -8750 | | Sana Iqbal | Engineering | 120000 | 122300 | 128750 | -8750 | | Priya Sharma | Engineering | 95000 | 122300 | 128750 | -33750 | | Kavya Reddy | HR | 90000 | 122300 | 77500 | 12500 | | Imran Shaikh | HR | 65000 | 122300 | 77500 | -12500 | | Anita Desai | Management | 250000 | 122300 | 250000 | 0 | | Farhan Ali | Sales | 140000 | 122300 | 101000 | 39000 | | Lata Joshi | Sales | 85000 | 122300 | 101000 | -16000 | | Tom Mathew | Sales | 78000 | 122300 | 101000 | -23000 | +--------------+-------------+--------+-------------+----------+---------+
Anatomy of a window function
function() OVER (PARTITION BY … ORDER BY … frame)
- functionAVG, SUM, COUNT, ROW_NUMBER, RANK, LAG…
- PARTITION BYsplit rows into groups (like GROUP BY, but rows stay)
- ORDER BYorder within each partition – needed for ranking and running totals
- framewhich neighbouring rows count (next lesson)
An empty OVER () means "all rows". Compare this with chapter 6, where the company average needed a subquery.
ROW_NUMBER, RANK and DENSE_RANK
SELECT name,
salary,
ROW_NUMBER() OVER (ORDER BY salary DESC, emp_id) AS row_num,
RANK() OVER (ORDER BY salary DESC) AS rnk,
DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rnk
FROM employees
WHERE department IN ('Engineering', 'Sales')
ORDER BY row_num;
+--------------+--------+---------+-----+-----------+ | name | salary | row_num | rnk | dense_rnk | +--------------+--------+---------+-----+-----------+ | Rohit Mehta | 180000 | 1 | 1 | 1 | | Farhan Ali | 140000 | 2 | 2 | 2 | | Sana Iqbal | 120000 | 3 | 3 | 3 | | Dev Patel | 120000 | 4 | 3 | 3 | | Priya Sharma | 95000 | 5 | 5 | 4 | | Lata Joshi | 85000 | 6 | 6 | 5 | | Tom Mathew | 78000 | 7 | 7 | 6 | +--------------+--------+---------+-----+-----------+
| Function | Ties | After a tie | Sequence here |
|---|---|---|---|
ROW_NUMBER() | different numbers (arbitrary order) | continues | 1, 2, 3, 4, 5… |
RANK() | same rank | skips numbers | 1, 2, 3, 3, 5… |
DENSE_RANK() | same rank | no gaps | 1, 2, 3, 3, 4… |
ROW_NUMBER and ties
Sana and Dev earn the same. Without a tie-breaker, which of them gets row 3 is arbitrary and may change between runs – that's why the query above orders by salary DESC, emp_id inside ROW_NUMBER's window. Always add a unique tie-breaker when you rely on ROW_NUMBER.
Top N per group
"The highest-paid person in each department" or "the 2 best-selling products per category" – rank within each partition, then filter the rank in an outer query (window functions can't be used directly in WHERE):
WITH ranked AS (
SELECT name, department, salary,
DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rnk
FROM employees
)
SELECT department, name, salary, rnk
FROM ranked
WHERE rnk <= 2
ORDER BY department, rnk, name;
+-------------+--------------+--------+-----+ | department | name | salary | rnk | +-------------+--------------+--------+-----+ | Engineering | Rohit Mehta | 180000 | 1 | | Engineering | Dev Patel | 120000 | 2 | | Engineering | Sana Iqbal | 120000 | 2 | | HR | Kavya Reddy | 90000 | 1 | | HR | Imran Shaikh | 65000 | 2 | | Management | Anita Desai | 250000 | 1 | | Sales | Farhan Ali | 140000 | 1 | | Sales | Lata Joshi | 85000 | 2 | +-------------+--------------+--------+-----+
Using DENSE_RANK keeps both Sana and Dev as Engineering's number 2. With ROW_NUMBER you'd get exactly two rows per department, arbitrarily dropping one of them.
Latest order per customer (again – the clean way)
SELECT customer_id, order_id, order_date, status
FROM (
SELECT o.*, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC, order_id DESC) AS rn
FROM orders o
) t
WHERE rn = 1
ORDER BY customer_id;
+-------------+----------+------------+-----------+ | customer_id | order_id | order_date | status | +-------------+----------+------------+-----------+ | 1 | 109 | 2025-10-21 | shipped | | 2 | 107 | 2025-10-03 | delivered | | 3 | 112 | 2025-11-06 | delivered | | 4 | 111 | 2025-11-05 | pending | | 5 | 106 | 2025-09-15 | shipped | | 6 | 108 | 2025-10-10 | pending | | 7 | 110 | 2025-11-02 | delivered | +-------------+----------+------------+-----------+
The Nth highest salary
"Find the second (or Nth) highest salary" is probably the most famous SQL interview question. With DENSE_RANK it's straightforward and handles ties correctly:
-- 3rd highest distinct salary
SELECT DISTINCT salary
FROM (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
FROM employees
) t
WHERE rnk = 3;
+--------+ | salary | +--------+ | 140000 | +--------+
-- Without window functions: classic answers interviewers also accept
SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
SELECT DISTINCT salary AS third_highest
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 2;
+----------------+ | second_highest | +----------------+ | 180000 | +----------------+ +---------------+ | third_highest | +---------------+ | 140000 | +---------------+
Practice
Try it yourself
Rank products by price within each category (highest first), showing the category's product count too.
Show solution
SELECT category_id, name, price, RANK() OVER (PARTITION BY category_id ORDER BY price DESC) AS price_rank, COUNT(*) OVER (PARTITION BY category_id) AS in_category FROM products WHERE category_id IS NOT NULL ORDER BY category_id, price_rank;+-------------+---------------------+---------+------------+-------------+ | category_id | name | price | price_rank | in_category | +-------------+---------------------+---------+------------+-------------+ | 1 | Mechanical Keyboard | 2499.00 | 1 | 4 | | 1 | Laptop Stand | 1499.00 | 2 | 4 | | 1 | USB-C Hub | 1299.00 | 3 | 4 | | 1 | Wireless Mouse | 599.00 | 4 | 4 | | 2 | JavaScript Guide | 550.00 | 1 | 3 | | 2 | Clean Code | 450.00 | 2 | 3 | | 2 | SQL in 10 Minutes | 350.00 | 3 | 3 | | 3 | Gel Pen Pack | 120.00 | 1 | 2 | | 3 | A5 Notebook | 90.00 | 2 | 2 | +-------------+---------------------+---------+------------+-------------+
Find the lowest-paid employee in each department.
Show solution
SELECT department, name, salary FROM ( SELECT department, name, salary, RANK() OVER (PARTITION BY department ORDER BY salary) AS r FROM employees ) t WHERE r = 1 ORDER BY department;+-------------+--------------+--------+ | department | name | salary | +-------------+--------------+--------+ | Engineering | Priya Sharma | 95000 | | HR | Imran Shaikh | 65000 | | Management | Anita Desai | 250000 | | Sales | Tom Mathew | 78000 | +-------------+--------------+--------+
Quick check
How does a window function differ from GROUP BY?
It computes over a set of rows but keeps every row instead of collapsing them.
Salaries 100, 90, 90, 80 – RANK and DENSE_RANK of 80?
RANK 4, DENSE_RANK 3.
Can you filter on a window function in WHERE?
No – compute it in a subquery or CTE and filter outside.
Summary
- OVER() turns aggregates into window functions; PARTITION BY groups without collapsing.
- ROW_NUMBER numbers rows, RANK leaves gaps after ties, DENSE_RANK doesn't.
- Top-N per group and Nth highest: rank in a CTE/subquery, then filter.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.