SQL Window Functions
Window functions let you perform calculations across rows related to the current row, without collapsing the result like GROUP BY does. Theyโre great for ranking, running totals, and more.
๐น Key Window Functions
ROW_NUMBER()โ assigns a unique sequential number to rows in a partitionRANK()โ ranks rows, with gaps for tiesDENSE_RANK()โ ranks rows without gapsNTILE(n)โ divides rows into n groupsLAG()/LEAD()โ access previous/next rowโs data
๐น Basic Syntax
SELECT
column1,
ROW_NUMBER() OVER (PARTITION BY partition_column ORDER BY order_column) AS row_num,
RANK() OVER (ORDER BY order_column DESC) AS rank
FROM table_name;PARTITION BYdivides data into groups (like GROUP BY, but rows remain visible)ORDER BYdefines row order within each partition
๐น Example: Ranking Employees by Salary in Each Department
SELECT
employee_name,
department_id,
salary,
ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC) AS row_num,
RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rank
FROM employees;ROW_NUMBERassigns unique rankRANKassigns same rank to ties, skips numbers after ties
๐ง Quick Recap
| Function | Description |
|---|---|
ROW_NUMBER() | Unique row number per partition |
RANK() | Ranking with gaps for ties |
DENSE_RANK() | Ranking without gaps |
NTILE(n) | Divides rows into n buckets |
LAG()/LEAD() | Access previous/next rowโs value |
๐ก Window functions power up your queries with advanced analytics โ all while keeping rows intact!
