100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
SQL Mastery
40 minbeginner

Window Functions: LEAD, LAG, SUM & AVG OVER

Beyond ranking, window functions can look across rows to compute running totals, moving averages, and comparisons between a row and its neighbours. These are the analytical staples behind trend lines and period-over-period reports: cumulative runs through an innings, a player's score compared to their previous match, or a moving average that smooths noisy data, all while keeping every detail row intact.

Two families do this work. The offset functions LEAD and LAG reach forward or backward to a neighbouring row, letting each row see the next or previous value. The aggregate window functions, SUM, AVG, COUNT and friends used with OVER, compute running and windowed aggregates over a sliding set of rows defined by a frame. Together they express almost any cross-row calculation analysts need.

These functions are where SQL becomes a genuine analytics language, doing work people often think requires a spreadsheet or Python. Running totals, growth rates, and rolling averages fall out of a single query, computed efficiently inside the database. Understanding offsets and frames is the final piece that lets you express sophisticated time-series and comparative analysis directly in SQL.

Analogy🏏Cricket
🏏 Think of it like cricket: Imagine the end of an IPL innings when the scorer announces the team's final total. Just as the scorer does not read out all one hundred and twenty individual deliveries but instead sums them into a single team score, SUM folds many row values into one number. Just as the commentator reports the highest individual score, the average partnership, and the number of wickets, MAX, AVG, and COUNT each summarise the innings differently. Just as a not-out batsman with no deliveries faced does not lower the team average, aggregates skip NULLs when computing. Just as the announcement is one figure no matter whether the innings had fifty deliveries or two hundred and fifty, an aggregate collapses any number of rows into a single result. This reveals why summaries answer the questions about the whole that individual deliveries cannot.
Lesson 32 of 35
0% complete