Function or operator · Advanced SQL

LAG

LAG returns a value from an earlier row in the order defined in OVER, while keeping the current row.

Before continuing: This entry is part of the window functions guide. If you are new to the topic, start with OVER.

LAG example

SQL
SELECT id,
       date,
       total,
       LAG(total) OVER (ORDER BY date, id) AS previous_total
FROM orders
WHERE customer_id = 3
ORDER BY date, id;

Check the result with small data

We have three measurements ordered by day.

Self-contained query · SQLite
WITH measurements(day, value) AS (
  VALUES (1,10),(2,14),(3,12)
)
SELECT day, value,
       LAG(value) OVER (ORDER BY day) AS previous
FROM measurements ORDER BY day;
Query result
dayvalueprevious
110NULL
21410
31214

LAG reads an earlier row without a self join. On the first day it returns NULL because this series has no earlier measurement.

Check your understanding: Which function would let you see the next day's value?

Show answer

LEAD(value) OVER (ORDER BY day): it reads the next row and returns NULL on the last day.

How LAG is used

The default offset is 1. When there is no earlier row, the result is NULL, unless you supply a default value.

What changes from case to case

Change from the previous order
SELECT id,
       total,
       total - LAG(total) OVER (ORDER BY date, id) AS change
FROM orders
WHERE customer_id = 3
ORDER BY date, id;

The first difference is also NULL. That does not mean zero: it means there is no earlier value to compare with.

Common mix-ups with LAG

Sorting only the output

Problem query
SELECT id, total,
       LAG(total) OVER () AS previous
FROM orders
ORDER BY date;

The ORDER BY outside the window sorts the output, but it does not define the window's sequence. PostgreSQL and SQLite accept a window with no explicit order, but the rows are then processed in an unspecified order; SQL Server requires ORDER BY for LAG. For portable, reproducible code, put it inside OVER. If dates can repeat, add a stable column such as id to break ties.

Comparing with the previous row can mark out whole sequences. The example on streaks of consecutive days with LAG removes repeated days, flags breaks and works out the start, end and length of each user's streak.