SQL LEAD, LAG & Value Functions: Time-Series & Trends

Analyzing financial trends, month-over-month revenue growth, and historical sequences requires comparing the current row's value against the preceding or following row. In legacy SQL, developers were forced to write slow self-joins. Modern SQL provides Value Window Functions: LAG(), LEAD(), FIRST_VALUE(), and LAST_VALUE().


1. LAG() Syntax & Month-Over-Month Variance

LAG() looks backward into prior rows:

LAG(column_name, [offset], [default_value]) OVER (ORDER BY sort_col)
-- Compare monthly revenue against the previous month
SELECT 
    sale_month,
    revenue,
    LAG(revenue, 1, 0) OVER (ORDER BY sale_month ASC) AS previous_month_revenue,
    revenue - LAG(revenue, 1, 0) OVER (ORDER BY sale_month ASC) AS monthly_growth
FROM monthly_sales;

2. LEAD() Syntax & Future Projections

LEAD() looks forward into upcoming rows:

-- View next scheduled appointment time
SELECT 
    patient_name,
    appointment_time,
    LEAD(appointment_time) OVER (ORDER BY appointment_time) AS next_patient_time
FROM clinic_schedule;

3. Calculating Cumulative Running Totals

Compute running cumulative sums by applying SUM() over an ordered window frame:

SELECT 
    order_date,
    daily_revenue,
    SUM(daily_revenue) OVER (
        ORDER BY order_date ASC
        ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    ) AS cumulative_running_revenue
FROM daily_sales;

Next, let us learn how to abstract complex queries using SQL Views & Materialized Views!

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!