Running Difference Window Lag
Compute period over period differences using the SQL LAG window function for sequential row comparison.
Code
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-levelWHEREwill 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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Date Difference CalculatorCalculate the number of days, weeks, whole months, and years between two ISO dates, computed in UTC.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- What are the relations in play here?
- `daily_revenue` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.