# Topic 47: Advanced Window Functions
LAG, LEAD, FIRST_VALUE, LAST_VALUE, running cumulative totals, and explicit ROWS frame boundaries.
1. Definition
Advanced Window Functions evaluate inter-row navigation (LAG/LEAD) and running cumulative calculations using custom frame specifications (ROWS BETWEEN).
2. Explain Like I'm 5
LAG looks in the rearview mirror at the previous car; LEAD looks through the windshield at the car ahead; running totals add up your bank balance as every transaction passes by.
3. Animation & Visual Simulation
Interactive Engine TraceAdvanced Window Functions Visual Simulator
SELECT date, amount,
LAG(amount) OVER (ORDER BY date) AS prev_amount,
SUM(amount) OVER (ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total
FROM sales;Active InputStep 1: Input & Parsing Stage
Initiating Advanced Window Functions
Checking Table Invariants
The database engine inspects active tables, verifies permissions, and prepares the physical operation.
4. Real-World Example
Calculating month-over-month revenue growth percentage and running year-to-date balances.
| Month | Revenue | LAG(Revenue) | MoM Growth |
|---|---|---|---|
| Jan 2026 | $10,000 | NULL | N/A |
| Feb 2026 | $12,000 | $10,000 | +20.0% |
| Mar 2026 | $15,000 | $12,000 | +25.0% |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectSELECT month, revenue, LAG(revenue, 1) OVER (ORDER BY month) AS prev_month_revenue, revenue - LAG(revenue, 1) OVER (ORDER BY month) AS mom_dollar_change FROM monthly_sales;
SELECT order_date, amount,
SUM(amount) OVER (
ORDER BY order_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_balance
FROM transactions;6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| LAG / LEAD Offsets | LAG(col, N, default) looks back N rows, returning the optional default value if no row exists. |
| ROWS vs RANGE | ROWS treats duplicate values as distinct physical rows; RANGE treats duplicates as identical tie groups. |
| Frame Default Trap | Specifying ORDER BY in OVER() without ROWS causes the frame to sum all tied rows simultaneously! |
| Default window frame hazard | Specifying ORDER BY without an explicit frame defaults to RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. |
| ROWS vs RANGE semantics | ROWS specifies a physical count of rows; RANGE specifies logical duplicate values based on the ORDER BY key. |
7. Deep Dive: The Critical Difference: ROWS BETWEEN vs RANGE BETWEEN
When calculating a running total on duplicate dates, the default RANGE frame groups identical dates together, calculating their combined sum on the first row! Using ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW forces strict physical row-by-row cumulative accumulation.
-- DANGEROUS: Jumps on duplicate dates: SUM(amount) OVER (ORDER BY date) -- PRECISE: Smooth physical running balance: SUM(amount) OVER (ORDER BY date, id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
8. Advantages & Disadvantages
Advantages
- •Eliminates slow, bug-prone self-joins for delta calculations.
- •Enables complex financial time-series analysis directly in SQL.
Disadvantages & Trade-offs
- •Window frames require careful boundary definitions to avoid unexpected duplicate behaviors.
9. Common Interview Questions
Q1.How do LEAD() and LAG() work and how do they eliminate expensive self-joins?
LEAD(col, offset, default) accesses data from a subsequent row at a specified offset within the partition without joining the table. LAG(col, offset, default) accesses data from a preceding row. They allow calculating period-over-period growth or time-between-events in a single O(N) streaming pass, replacing quadratic O(N^2) self-joins.
SELECT date, revenue, LAG(revenue, 1) OVER (ORDER BY date) AS prev_day_revenue, revenue - LAG(revenue, 1) OVER (ORDER BY date) AS daily_growth FROM daily_sales;
Q2.What is the difference between "ROWS BETWEEN" and "RANGE BETWEEN" in window frames?
ROWS operates on physical row offsets: ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING strictly looks at the 1 row physically before and 1 row physically after the current row. RANGE operates on value equality of the ORDER BY column: if multiple rows share the exact same value in the order key, RANGE treats all tied rows as a single frame boundary, often causing unexpected spikes in running totals.
Q3.How do you calculate a 7-day Moving Average of revenue in SQL?
You use an analytical window frame over sorted daily records:
SELECT
sale_date, daily_revenue,
AVG(daily_revenue) OVER (
ORDER BY sale_date
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS seven_day_moving_avg
FROM daily_revenue_table;Q4.What is NTILE(n) and what are its common production use cases?
NTILE(n) divides the sorted partition into n roughly equal buckets (quartiles, deciles, percentiles) and assigns a bucket number from 1 to n to each row. It is widely used in analytics to segment users into spending quartiles (NTILE(4)) or assign test cohorts.
Q5.What is FIRST_VALUE() vs LAST_VALUE() and why does LAST_VALUE() often surprise developers?
FIRST_VALUE(col) returns the first value in the window frame. LAST_VALUE(col) returns the last value in the window frame. Developers are often surprised when LAST_VALUE() simply returns the current row value! This happens because the default window frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW (the frame ends at the current row). To get the true last value of the partition, you must specify ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.
10. Interview-Ready Answer
“Advanced window functions like LAG and LEAD allow inter-row calculations without self-joins. When computing running totals, explicitly defining ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW guarantees strict row-by-row accumulation and avoids duplicate RANGE summation traps.”
11. Quick Test
What does LAG(price, 1, 0.0) return when evaluated on the very first row of a partition?