← Cheat Sheets
SQL Window Functions
Calculate across related rows without collapsing them.
# SQL Window Functions
Calculate across related rows without collapsing them.
```sql
SELECT name, department, salary,
ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn,
RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rnk,
DENSE_RANK() OVER (ORDER BY salary DESC) AS dense,
LAG(salary) OVER (ORDER BY hired_on) AS prev_salary,
LEAD(salary) OVER (ORDER BY hired_on) AS next_salary,
SUM(salary) OVER (PARTITION BY department) AS dept_total
FROM employees;
```
`RANK` leaves gaps after ties; `DENSE_RANK` does not.