Running Difference Window Lag

Compute period over period differences using the SQL LAG window function for sequential row comparison.

SqlData Fetching

Code

sqlsnippet
11 lines
SELECT
  date,
  revenue,
  revenue - LAG(revenue, 1, 0) OVER (ORDER BY date) AS daily_diff,
  ROUND(
    (revenue - LAG(revenue, 1, 0) OVER (ORDER BY date))
    / NULLIF(LAG(revenue, 1, 0) OVER (ORDER BY date), 0) * 100,
    2
  ) AS pct_change
FROM daily_revenue
ORDER BY date;

How the snippet works

What runs is SELECT, with daily_revenue as the object involved.

In terms of clauses, the statements use: a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.

What to watch for

  • Window functions evaluate after WHERE/GROUP BY, so filtering on their output in the same-level WHERE will not work — use an outer query or a CTE.

Applying it

Run the statement against the daily_revenue table.

Statements that matter

SELECT
date,
revenue,
revenue - LAG(revenue, 1, 0) OVER (ORDER BY date) AS daily_diff,
ROUND(
(revenue - LAG(revenue, 1, 0) OVER (ORDER BY date))
/ NULLIF(LAG(revenue, 1, 0) OVER (ORDER BY date), 0) * 100,
2
) AS pct_change
FROM daily_revenue
ORDER BY date;

Interactive Tools for This Topic

FAQ

What are the relations in play here?
`daily_revenue` — referenced directly, no join needed.