Skip to content
Back to 50 Concepts
Topic 47 of 50query-executionAdvanced

# 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).

Relational Invariant:Deterministic relational algebra contract evaluated by the Cost-Based Optimizer.

2. Explain Like I'm 5

Intuitive mental model for beginners

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 Trace
Interactive Engine Simulation

Advanced Window Functions Visual Simulator

Step 1 of 3
SQL>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 Input

Step 1: Input & Parsing Stage

Engine Action: Validate SQL syntax and resolve schema metadata for Advanced Window Functions
SQL Input

Initiating Advanced Window Functions

Schema Catalog

Checking Table Invariants

How the Database Executes This:

The database engine inspects active tables, verifies permissions, and prepares the physical operation.

💡 Conveyor belt: As items pass by, LAG looks at the item that just left, LEAD looks at the item arriving next, and the running total weighs everything that has passed so far.

4. Real-World Example

Calculating month-over-month revenue growth percentage and running year-to-date balances.

Month over Month Growth
MonthRevenueLAG(Revenue)MoM Growth
Jan 2026$10,000NULLN/A
Feb 2026$12,000$10,000+20.0%
Mar 2026$15,000$12,000+25.0%
Relational walkthrough: LAG(revenue, 1) fetches the previous month without requiring a complex self-join.

5. SQL Syntax

ANSI SQL / PostgreSQL Dialect
Step 1: Inter-row navigation with LAG and LEAD
SELECT 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;
Step 2: Cumulative Running Total with ROWS Frame
SELECT order_date, amount,
  SUM(amount) OVER (
    ORDER BY order_date
    ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  ) AS running_balance
FROM transactions;
Explicit ROWS BETWEEN avoids RANGE duplicate summation surprises.

6. Important Rules & Behaviors

RuleBehavioral Explanation
LAG / LEAD OffsetsLAG(col, N, default) looks back N rows, returning the optional default value if no row exists.
ROWS vs RANGEROWS treats duplicate values as distinct physical rows; RANGE treats duplicates as identical tie groups.
Frame Default TrapSpecifying ORDER BY in OVER() without ROWS causes the frame to sum all tied rows simultaneously!
Default window frame hazardSpecifying ORDER BY without an explicit frame defaults to RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.
ROWS vs RANGE semanticsROWS 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)
Caution: Always specify ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW for financial running balances.

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

Scenario Question:

What does LAG(price, 1, 0.0) return when evaluated on the very first row of a partition?

Select your answer: