// SQL snippet

Month-over-month delta

LAG walks the previous row of the monthly series; the delta is a subtraction away.

Main statement
PostgreSQL

The task

You want each month's revenue next to the previous month's, the difference, and the percent change, ready for a dashboard.

The snippet

Written for PostgreSQL.

PostgreSQL
WITH monthly AS (
  SELECT DATE_TRUNC('month', order_date)::date AS month,
         SUM(amount) AS month_total
  FROM orders
  GROUP BY 1
)
SELECT month, month_total,
       month_total - LAG(month_total) OVER (ORDER BY month) AS delta,
       ROUND(100.0 * (month_total - LAG(month_total) OVER (ORDER BY month))
             / NULLIF(LAG(month_total) OVER (ORDER BY month), 0), 1) AS pct_change
FROM monthly
ORDER BY month;

So funktioniert es

LAG(month_total) looks one row back in the month-ordered series and returns NULL for the first row, so the delta starts as NULL rather than zero. NULLIF turns a zero previous month into NULL, which avoids a division-by-zero error in the percentage. If a month can be missing entirely, fill it from a calendar spine first or LAG will compare across the gap.

Variations

Compare to the same month last year

WITH monthly AS (
  SELECT DATE_TRUNC('month', order_date)::date AS month,
         SUM(amount) AS month_total
  FROM orders
  GROUP BY 1
)
SELECT month, month_total,
       month_total - LAG(month_total, 12) OVER (ORDER BY month) AS delta_vs_last_year
FROM monthly
ORDER BY month;

Questions that come up

Why is the first row's delta NULL?

LAG has no previous row to read, so it returns NULL by default. You can pass a default as the third argument (LAG(month_total, 1, 0)) but treating the first month as 'no change yet' is usually more honest than showing a fake delta.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.