Analytical or window functions add insights across rows without collapsing the dataset. They power comparisons, time-series analysis, dashboards, and QA validation where the original row structure must stay intact.
Analytical functions operate over a window defined by OVER (PARTITION BY ... ORDER BY ...). They return a value per row instead of aggregating multiple rows into one result.
| ID | Region | Month | Sales |
|---|---|---|---|
| 1 | East | Jan | 1000 |
| 2 | East | Feb | 1500 |
| 3 | East | Mar | 1200 |
| 4 | West | Jan | 2000 |
| 5 | West | Feb | 2500 |
| 6 | West | Mar | 1800 |
SELECT
Region,
Month,
Sales,
LAG(Sales, 1) OVER (PARTITION BY Region ORDER BY Month) AS PrevMonthSales,
Sales - LAG(Sales, 1) OVER (PARTITION BY Region ORDER BY Month) AS SalesChange
FROM Sales;
NULL. Use COALESCE if you need a default value.SELECT
Region,
Month,
Sales,
LEAD(Sales, 1) OVER (PARTITION BY Region ORDER BY Month) AS NextMonthSales
FROM Sales;
SELECT
Region,
Month,
Sales,
FIRST_VALUE(Sales) OVER (PARTITION BY Region ORDER BY Month) AS FirstMonthSales
FROM Sales;
SELECT
Region,
Month,
Sales,
LAST_VALUE(Sales) OVER (
PARTITION BY Region
ORDER BY Month
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS LastMonthSales
FROM Sales;
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING, LAST_VALUE only considers the current window frame.SELECT
Region,
Month,
Sales,
LAG(Sales) OVER (PARTITION BY Region ORDER BY Month) AS Prev,
LEAD(Sales) OVER (PARTITION BY Region ORDER BY Month) AS Next,
FIRST_VALUE(Sales) OVER (PARTITION BY Region ORDER BY Month) AS First,
LAST_VALUE(Sales) OVER (
PARTITION BY Region ORDER BY Month
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS Last
FROM Sales;
Compare month-over-month growth with LAG and LEAD.
Highlight first and last values to spotlight opening and closing metrics.
Validate API responses that include previous/next period totals.
Monitor salary revisions or balance changes without losing row detail.
ORDER BY so the window has a deterministic sequence.LAG/LEAD.GROUP BY does.”