AI Hints
Home›PostgreSQL Tutorial›Window Functions
PostgreSQL · Lesson 33 of 120

Running Totals and LAG

Looking back.

⏱ 2 min read▶ Video at 28:45🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

The owner wants monthly revenue, a running total for the year, and the change from last month. Window functions do all three in one query.

  • Monthly revenue
  • Running total
  • vs last month

Monthly trend

The CTE totals revenue per month. Sum over order by month gives a running total. Lag looks at the previous row, so we can see the change. Run it. The first five months of twenty twenty five.

query.sqlsql
WITH monthly AS (
  SELECT date_trunc('month', o.order_date)::date AS month,
         sum(i.quantity * b.price) AS revenue
  FROM orders o JOIN order_items i USING (order_id)
  JOIN books b USING (book_id)
  WHERE o.order_date BETWEEN '2025-01-01' AND '2025-05-31'
  GROUP BY 1
)
SELECT month, revenue,
       sum(revenue) OVER (ORDER BY month) AS running,
       revenue - lag(revenue) OVER (ORDER BY month) AS change
FROM monthly ORDER BY month;
Output
   month    | revenue | running  | change
------------+---------+----------+---------
 2025-01-01 | 2120.24 |  2120.24 |
 2025-02-01 | 2465.13 |  4585.37 |  344.89
 2025-03-01 | 1952.82 |  6538.19 | -512.31
 2025-04-01 | 2334.68 |  8872.87 |  381.86
 2025-05-01 | 3019.79 | 11892.66 |  685.11
(5 rows)

Looking around

Lag looks at the previous row, and lead at the next one. First value and last value look at the edges. And a frame, like rows between two preceding and current row, makes moving averages.

keyvalue
lag()previous row
lead()next row
first_value()window start
ROWS BETWEENmoving averages

Summary

Running sums and lag turn plain totals into trends. Next, a Postgres favourite, distinct on.

Key takeaways
  • sum() OVER
  • lag()
  • Trends
Next up: DISTINCT ON — one row per group