SQL & Relational Databases (50 Qs)•Part 3: Advanced Internals, Scale & Production Patterns (Senior / Lead)
SQL Window Functions: `ROW_NUMBER()`, `RANK()`, `DENSE_RANK()`, `LEAD()`, and `LAG()`.
senior LevelCode ExampleDatabases & SQL
In Simple Words:
Window functions perform calculations across a set of table rows related to the current row without collapsing the rows into a single group like GROUP BY does:
ROW_NUMBER(): Assigns a unique sequential integer (1, 2, 3, 4) to each row within a partition.RANK(): Assigns ranks with gaps for ties (1, 2, 2, 4).DENSE_RANK(): Assigns ranks without gaps for ties (1, 2, 2, 3).LEAD(col, offset)/LAG(col, offset): Accesses data from a subsequent or preceding row without performing a self-join.
sql
-- Finding the top 2 highest-paid employees in each department
WITH RankedSalaries AS (
SELECT
employee_id,
department_id,
salary,
DENSE_RANK() OVER (
PARTITION BY department_id
ORDER BY salary DESC
) AS salary_rank
FROM employees
)
SELECT * FROM RankedSalaries WHERE salary_rank <= 2;