Window functions perform calculations across a set of rows related to the current row—without collapsing the results the way GROUP BY does. They are ideal for rankings, running totals, moving averages, and comparing the current row to previous or next rows.
function_name(expression) OVER (
[PARTITION BY column]
[ORDER BY column]
[ROWS | RANGE frame]
);
GROUP BY).| Function | Purpose | Typical Use |
|---|---|---|
ROW_NUMBER() |
Assigns a unique sequential number | Pagination or deterministic ordering |
RANK() / DENSE_RANK() |
Assigns ranks with or without gaps | Leaderboards, competition results |
NTILE(n) |
Splits rows into n buckets | Quartiles, percentiles |
SUM(), AVG(), COUNT() |
Calculates running totals or moving averages | Sales analysis, time-based metrics |
LAG() / LEAD() |
Accesses previous or next row values | Trend and variance comparisons |
SELECT
employee_id,
department_id,
salary,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC
) AS rank_in_dept
FROM employees;
SELECT
order_id,
customer_id,
order_date,
SUM(amount) OVER (
PARTITION BY customer_id
ORDER BY order_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_total
FROM orders;
LAGSELECT
product_id,
month,
sales,
LAG(sales) OVER (
PARTITION BY product_id
ORDER BY month
) AS prev_month_sales,
sales - LAG(sales) OVER (
PARTITION BY product_id
ORDER BY month
) AS sales_change
FROM sales_data;
SELECT
name,
department,
salary,
RANK() OVER (
PARTITION BY department
ORDER BY salary DESC
) AS rank_in_dept
FROM employees;
GROUP BY, window functions keep all detail rows visible.