SQL Window Functions
Visualize how calculations are performed across a set of table rows that are somehow related to the current row.
Data Preview (Source + Result)
READY
Visualize how calculations are performed across a set of table rows that are somehow related to the current row.
Go beyond `GROUP BY` to perform calculations across sets of rows while keeping the original rows intact. This guide will make you an expert.
Window functions are a powerful feature in SQL that perform a calculation across a set of table rows that are somehow related to the current row. Unlike aggregate functions (`SUM`, `COUNT`), which collapse rows into a single output row, window functions return a value for every single row.
The magic of window functions is the `OVER()` clause. This clause defines the "window" or set of rows the function should consider for its calculation. It has two key components:
For each row, the function calculates its result based on the other rows in its "window" (its partition).
The visualizer helps you see how the `PARTITION BY` and `ORDER BY` clauses define the calculation for each row.
Window functions are essential for advanced analysis. Here are some classic problems they solve:
-- Find the top 3 selling employees in each region
SELECT * FROM (
SELECT Name, Region, Sales,
RANK() OVER (PARTITION BY Region ORDER BY Sales DESC) as rank_num
FROM SalesData
) AS ranked_sales
WHERE rank_num <= 3;
-- Calculate month-over-month sales growth for each department
SELECT Dept, Month, Sales,
Sales - LAG(Sales, 1, 0) OVER (PARTITION BY Dept ORDER BY Month) as sales_growth
FROM MonthlySales;
Go beyond `GROUP BY` to perform calculations across sets of rows while keeping the original rows intact. This guide will make you an expert.