Window functions perform calculations across rows related to the current row without collapsing data, unlike
GROUP BY.1๏ธโฃ ROW_NUMBER()
Assigns a unique number to each row within a partition.
SELECT name, dept_id,
ROW_NUMBER() OVER (
PARTITION BY dept_id
ORDER BY salary DESC
) AS rank
FROM employees;
๐ *Use case:* Rank employees by salary within each department.
2๏ธโฃ RANK() vs DENSE_RANK()
โข
RANK() โ Skips numbers on ties (1, 2, 2, 4)โข
DENSE_RANK() โ No gaps (1, 2, 2, 3)SELECT name, salary,
RANK() OVER (ORDER BY salary DESC) AS rnk,
DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rnk
FROM employees;
3๏ธโฃ LAG() & LEAD()
Access previous or next row values.
SELECT name, salary,
LAG(salary) OVER (ORDER BY id) AS prev_salary,
LEAD(salary) OVER (ORDER BY id) AS next_salary
FROM employees;
๐ Use case: Compare current vs previous/next values
(e.g., salary change, stock price movement).
4๏ธโฃ NTILE(n)
Divides rows into *n* equal buckets.
SELECT name,
NTILE(4) OVER (ORDER BY salary DESC) AS quartile
FROM employees;
๐ Use case: Quartiles & percentile-based analysis.
5๏ธโฃ Aggregates with OVER()
Running totals & partition-wise calculations.
SELECT name, dept_id, salary,
SUM(salary) OVER (PARTITION BY dept_id) AS dept_total
FROM employees;
๐ง Interview Q&A
Q1๏ธโฃ GROUP BY vs OVER()?
โข
GROUP BY โ Collapses rows (one row per group)โข
OVER() โ Keeps all rows and adds calculated columnsQ2๏ธโฃ When to use LAG()?
To compare current row with previous data
(e.g., daily revenue change, previous month balance).
Q3๏ธโฃ No PARTITION BY used?
The function runs over the entire result set.
Q4๏ธโฃ Can we use ORDER BY inside OVER()?
โ Yes. Required for ranking, LAG/LEAD, running totals.
๐ฌ Double tap โค๏ธ & share for more SQL tips! ๐