Skip to main content

Lag and lead in duckdb

sql
data analysis
Author

Joram Mutenge

Published

2026-12-05

One of the most powerful features of window functions is the ability to compare a row with another row in the same result set. Instead of treating each row in isolation, functions like LAG and LEAD allow me to “look backward” or “look forward” within an ordered set of data.

I’ll use the (https://github.com/jorammutenge/learn-rust/blob/main/sample_sales.csv)[clothing store sales dataset] to answer some business questions using these two functions. Let me load the data into a table called sales.

CREATE TEMP TABLE sales AS (
    SELECT * FROM read_csv_auto('https://raw.githubusercontent.com/jorammutenge/learn-rust/refs/heads/main/sample_sales.csv')
);

Finally I’ll rename some columns to remove spaces in their names.

ALTER TABLE sales RENAME COLUMN "Account Name" TO account_name;
ALTER TABLE sales RENAME COLUMN "unit price" TO unit_price;
ALTER TABLE sales RENAME COLUMN "ext price" TO ext_price;

LAG

The syntax for LAG is:

LAG(
    expression,
    offset,
    default
)

Where:

  • expression = the value to retrieve
  • offset = how many rows back to look
  • default = value returned when no previous row exists

For example:

LAG(revenue, 1, revenue)

means:

expression = revenue offset = 1 row back default = current row’s value

This avoids a NULL on the first row because DuckDB uses the current row’s revenue whenever a previous row doesn’t exist.

With this understanding, I can answer a business question like: How did total revenue change compared to the previous day?

This is one of the most common uses of LAG. I can calculate daily revenue and compare it to the prior day’s revenue.

WITH daily_sales AS (
    SELECT
        CAST(date AS DATE) AS sales_date,
        SUM(ext_price) AS revenue
    FROM sales
    GROUP BY 1
)

SELECT
    sales_date,
    revenue,
    LAG(revenue) OVER (
        ORDER BY sales_date
    ) AS previous_day_revenue,
    ROUND(
        revenue -
        LAG(revenue) OVER (
            ORDER BY sales_date
        ),
        2
    ) AS revenue_change
FROM daily_sales
ORDER BY sales_date;
┌────────────┬────────────────────┬──────────────────────┬────────────────┐
│ sales_date │      revenue       │ previous_day_revenue │ revenue_change │
│    date    │       double       │        double        │     double     │
├────────────┼────────────────────┼──────────────────────┼────────────────┤
│ 2013-09-30 │             543.24 │                 NULL │           NULL │
│ 2013-10-01 │             905.32 │               543.24 │         362.08 │
│ 2013-10-03 │  682.3199999999999 │               905.32 │         -223.0 │
│ 2013-10-04 │            2278.66 │    682.3199999999999 │        1596.34 │
│ 2013-10-05 │            1174.26 │              2278.66 │        -1104.4 │
│     ·      │                ·   │                 ·    │           ·    │
│     ·      │                ·   │                 ·    │           ·    │
│     ·      │                ·   │                 ·    │           ·    │
│ 2014-09-26 │             1309.1 │              2059.28 │        -750.18 │
│ 2014-09-27 │            1984.79 │               1309.1 │         675.69 │
│ 2014-09-28 │             355.94 │              1984.79 │       -1628.85 │
│ 2014-09-29 │ 2108.2200000000003 │               355.94 │        1752.28 │
│ 2014-09-30 │            2162.52 │   2108.2200000000003 │           54.3 │
└────────────┴────────────────────┴──────────────────────┴────────────────┘
  352 rows (10 shown)      use .last to show entire result      4 columns

This immediately highlights days where revenue surged or dropped relative to the previous trading day. For instance, I can see in the second row that revenue increased from the previous day. That’s why the revenue_change column shows a positive value 362.08.

Another business question I could answer is: How does each category’s revenue compare to its previous sales day?

This involves reseting the comparison for each category.

WITH daily_category_sales AS (
    SELECT
        CAST(date AS DATE) AS sales_date,
        category,
        SUM(ext_price) AS revenue
    FROM sales
    GROUP BY 1, 2
)

SELECT
    sales_date,
    category,
    revenue,
    LAG(revenue) OVER (
        PARTITION BY category
        ORDER BY sales_date
    ) AS previous_category_revenue
FROM daily_category_sales
ORDER BY category, sales_date;
┌────────────┬──────────┬────────────────────┬───────────────────────────┐
│ sales_date │ category │      revenue       │ previous_category_revenue │
│    date    │ varchar  │       double       │          double           │
├────────────┼──────────┼────────────────────┼───────────────────────────┤
│ 2013-10-05 │ Hat      │              423.3 │                      NULL │
│ 2013-10-07 │ Hat      │             281.82 │                     423.3 │
│ 2013-10-09 │ Hat      │              46.11 │                    281.82 │
│ 2013-10-12 │ Hat      │            1575.36 │                     46.11 │
│ 2013-10-13 │ Hat      │             209.76 │                   1575.36 │
│     ·      │  ·       │                ·   │                      ·    │
│     ·      │  ·       │                ·   │                      ·    │
│     ·      │  ·       │                ·   │                      ·    │
│ 2014-09-26 │ Sweater  │            1115.32 │         848.4200000000001 │
│ 2014-09-27 │ Sweater  │             847.29 │                   1115.32 │
│ 2014-09-28 │ Sweater  │             256.96 │                    847.29 │
│ 2014-09-29 │ Sweater  │ 1594.8600000000001 │                    256.96 │
│ 2014-09-30 │ Sweater  │ 1417.6799999999998 │        1594.8600000000001 │
└────────────┴──────────┴────────────────────┴───────────────────────────┘
  639 rows (10 shown)     use .last to show entire result      4 columns

From this result set, I can answer questions such as: Did Sweater revenue increase compared to the last day Sweaters were sold?

It’s worth noting that the comparison is performed independently for each category.

LEAD

LEAD uses the same syntax as LAG:

LEAD(
    expression,
    offset,
    default
)

However, instead of looking backward, it looks forward. For example:

LEAD(revenue, 1, revenue)

means:

expression = revenue offset = 1 row ahead default = current row’s value

A business question I can answer is: What was the revenue on the next sales day?

This is the forward-looking equivalent of the first example.

WITH daily_sales AS (
    SELECT
        CAST(date AS DATE) AS sales_date,
        SUM(ext_price) AS revenue
    FROM sales
    GROUP BY 1
)

SELECT
    sales_date,
    revenue,
    LEAD(revenue) OVER (
        ORDER BY sales_date
    ) AS next_day_revenue
FROM daily_sales
ORDER BY sales_date;
┌────────────┬────────────────────┬────────────────────┐
│ sales_date │      revenue       │  next_day_revenue  │
│    date    │       double       │       double       │
├────────────┼────────────────────┼────────────────────┤
│ 2013-09-30 │             543.24 │             905.32 │
│ 2013-10-01 │             905.32 │  682.3199999999999 │
│ 2013-10-03 │  682.3199999999999 │            2278.66 │
│ 2013-10-04 │            2278.66 │            1174.26 │
│ 2013-10-05 │            1174.26 │  860.5799999999999 │
│     ·      │                ·   │               ·    │
│     ·      │                ·   │               ·    │
│     ·      │                ·   │               ·    │
│ 2014-09-26 │             1309.1 │            1984.79 │
│ 2014-09-27 │            1984.79 │             355.94 │
│ 2014-09-28 │             355.94 │ 2108.2200000000003 │
│ 2014-09-29 │ 2108.2200000000003 │            2162.52 │
│ 2014-09-30 │            2162.52 │               NULL │
└────────────┴────────────────────┴────────────────────┘
  352 rows (10 shown)                        3 columns

From the result set, I can directly compare today’s revenue with the following sales day’s revenue.

Another business question I can answer with LEAD is: Which transaction came immediately after each sale for a customer?

SELECT
    account_name,
    date,
    ext_price,
    LEAD(ext_price) OVER (
        PARTITION BY account_name
        ORDER BY date
    ) AS next_purch_amt
FROM sales
ORDER BY account_name, date;
┌───────────────────────────┬─────────────────────┬───────────┬────────────────┐
│       account_name        │        date         │ ext_price │ next_purch_amt │
│          varchar          │      timestamp      │  double   │     double     │
├───────────────────────────┼─────────────────────┼───────────┼────────────────┤
│ Abbott PLC                │ 2014-03-18 16:11:54 │    755.44 │           NULL │
│ Abbott, Rogahn and Bednar │ 2014-02-23 12:50:34 │     615.6 │           NULL │
│ Abshire LLC               │ 2013-10-27 09:48:10 │     90.34 │         720.18 │
│ Abshire LLC               │ 2013-12-25 01:45:45 │    720.18 │           NULL │
│ Altenwerth, Stokes and P… │ 2014-06-25 07:38:43 │    843.31 │           NULL │
│             ·             │          ·          │       ·   │             ·  │
│             ·             │          ·          │       ·   │             ·  │
│             ·             │          ·          │       ·   │             ·  │
│ Ziemann, Reynolds and Mc… │ 2013-12-19 20:21:33 │    665.35 │           NULL │
│ Zieme-Corkery             │ 2014-04-24 18:46:04 │     482.9 │           NULL │
│ Zieme-Romaguera           │ 2013-11-20 13:59:21 │    260.13 │           NULL │
│ Zulauf-Will               │ 2014-05-05 07:36:02 │     163.4 │         1246.8 │
│ Zulauf-Will               │ 2014-06-07 21:09:16 │    1246.8 │           NULL │
└───────────────────────────┴─────────────────────┴───────────┴────────────────┘
  1000 rows (10 shown)        use .last to show entire result        4 columns

From this result set, I can trace customer purchasing behavior over time and see what purchase amount followed each transaction.

Comparing LAG and LEAD

Sometimes it’s useful to look both backward and forward simultaneously. I can ask a business question like: How does a day’s revenue compare to both the previous and next sales days?

WITH daily_sales AS (
    SELECT
        CAST(date AS DATE) AS sales_date,
        SUM(ext_price) AS revenue
    FROM sales
    GROUP BY 1
)

SELECT
    sales_date,
    revenue,
    LAG(revenue) OVER (
        ORDER BY sales_date
    ) AS previous_revenue,
    LEAD(revenue) OVER (
        ORDER BY sales_date
    ) AS next_revenue
FROM daily_sales
ORDER BY sales_date;
┌────────────┬────────────────────┬────────────────────┬────────────────────┐
│ sales_date │      revenue       │  previous_revenue  │    next_revenue    │
│    date    │       double       │       double       │       double       │
├────────────┼────────────────────┼────────────────────┼────────────────────┤
│ 2013-09-30 │             543.24 │               NULL │             905.32 │
│ 2013-10-01 │             905.32 │             543.24 │  682.3199999999999 │
│ 2013-10-03 │  682.3199999999999 │             905.32 │            2278.66 │
│ 2013-10-04 │            2278.66 │  682.3199999999999 │            1174.26 │
│ 2013-10-05 │            1174.26 │            2278.66 │  860.5799999999999 │
│     ·      │                ·   │               ·    │               ·    │
│     ·      │                ·   │               ·    │               ·    │
│     ·      │                ·   │               ·    │               ·    │
│ 2014-09-26 │             1309.1 │            2059.28 │            1984.79 │
│ 2014-09-27 │            1984.79 │             1309.1 │             355.94 │
│ 2014-09-28 │             355.94 │            1984.79 │ 2108.2200000000003 │
│ 2014-09-29 │ 2108.2200000000003 │             355.94 │            2162.52 │
│ 2014-09-30 │            2162.52 │ 2108.2200000000003 │               NULL │
└────────────┴────────────────────┴────────────────────┴────────────────────┘
  352 rows (10 shown)       use .last to show entire result       4 columns

The result set above creates a three-day view:

Previous Day | Current Day | Next Day

making trend analysis much easier.

What to remember

LAG and LEAD are among the most practical window functions in DuckDB because they allow a row to reference other rows without performing self-joins. LAG looks backward in an ordered dataset, while LEAD looks forward. When combined with PARTITION BY, they provide independent histories for groups such as categories, customers, or products. It doesn’t matter if you’re measuring day-over-day revenue changes, comparing customer purchases, or tracking category performance, these functions make it easy to understand how values evolve over time with remarkably little SQL code.