Window functions are one of SQL's most powerful features — and one of the most asked about in advanced SQL interviews. They let you compute aggregates, rankings, and comparisons without collapsing your rows.
Assigns a unique sequential integer to each row within a partition.
SELECT first_name, department, salary,
ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rank_in_dept
FROM employees;RANK() leaves gaps: 1, 2, 2, 4
DENSE_RANK() no gaps: 1, 2, 2, 3
SELECT name, salary,
RANK() OVER (ORDER BY salary DESC) AS rank,
DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rank
FROM employees;LAG accesses a previous row's value. LEAD accesses a next row's value. Essential for period-over-period comparisons.
WITH monthly AS (
SELECT SUBSTR(order_date,1,7) AS month,
ROUND(SUM(total),2) AS revenue
FROM orders GROUP BY month
)
SELECT month, revenue,
LAG(revenue) OVER (ORDER BY month) AS prev_month,
ROUND(revenue - LAG(revenue) OVER (ORDER BY month), 2) AS change
FROM monthly ORDER BY month;Run all the queries from this article in our free SQL playground.
Open SQL Playground →