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!