liveBook · Manning

Lag

As explained in DuckDB in Action

lag is a window function that returns a value from a preceding row in an ordered window partition.

lag() returns an expression’s value from the row preceding the current row in an ordered window partition, or NULL for the partition’s first row. Pair it with an ordered date column to compare successive observations. section 4.5.4 section 4.5

Compare successive energy prices

For monthly 2019 energy prices, lag(value) produces the previous month’s price; subtracting it from value exposes each period’s change. Use lag(value, 1, value) when the first row should produce a zero change instead of NULL. To sum those changes, calculate them in a CTE before applying sum(), because window functions cannot be nested inside aggregate functions.

Listing 4.19 Computing lagging and leading values of windows
SELECT valid_from,
       value,
       lag(value)  #1
         OVER validity AS "Previous value",
       value - lag(value, 1, value)
         OVER validity AS Change  #2

FROM prices
WHERE date_part('year', valid_from) = 2019
WINDOW validity AS (ORDER BY valid_from)
ORDER BY valid_from;

Inspect the runnable query showing previous values, default handling, ordering, and calculated changes. section 4.5.4

How DuckDB in Action covers it

How deep it goes
Defines preceding-row access, NULL behavior, defaults, and CTE aggregation while deferring broader implementation internals.
Examples
Uses monthly renewable-energy prices to display previous values, period changes, and a yearly total.
What it assumes
Assumes familiarity with SQL queries and introduces windows, ordering, partitions, NULL defaults, and CTE-based aggregation.
What you can do after
Apply it in DuckDB SQL to compare ordered rows and aggregate derived changes through a CTE.
How it connects
Connects lag to window functions, partitions, ordering, lead, coalesce, aggregate functions, and common table expressions.

Also explained in

Compare how 5 books explain lag →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of DuckDB in Action. The section links point to the parts of the book it draws on.