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().
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;
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;
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!
LAG(column, offset, default) accesses data from a previous row in the partition at a specified physical offset (default offset is 1) without requiring a self-join.
LEAD(column, offset, default) accesses data from a subsequent (following) row in the partition at a specified offset.
Use SUM(amount) OVER (ORDER BY date_column ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW).
Proceed to the next class in sequence to build production mastery of relational database architecture.
Continue to Class 44: Views & Materialized Views → Previous: ← Window Functions | Full Syllabus
PARTITION BY and OVER clause mechanics.
Wrapping LEAD/LAG calculations for downstream filtering.
Calculating days between customer purchases with LAG.
Indexing window PARTITION BY and ORDER BY columns.