Programming

Use PostgreSQL `LAG()` to Compare Each Row with the Previous Row Without Losing Detail

Use PostgreSQL’s `LAG()` window function to add a previous-row value and a row-by-row difference to detailed query results. Build a reproducible time-series example, define a stable row order, and handle the first row in each group.

A common reporting task is to compare each event, reading, or transaction with the one immediately before it. You might want to show how much an account balance changed since its previous observation, or which status was recorded before the current one.

A grouped aggregate can summarize rows, but that is not the result you want when every original row must remain visible. PostgreSQL’s LAG() is a window function: it lets a query retrieve a value from a preceding row while returning the current row’s selected details as well. PostgreSQL documents window functions as an advanced SQL feature; LAG() is specifically used to compare a row with a prior row rather than collapsing the result into aggregates.

This tutorial builds a query for daily meter readings. It shows the previous reading beside each current reading, calculates the change, and handles ordering, groups, missing prior rows, and duplicate timestamps.

The example: show every reading and its previous value

Start with a table in which each meter can have multiple readings:

CREATE TEMP TABLE meter_readings (
    reading_id  integer PRIMARY KEY,
    meter_id    integer NOT NULL,
    recorded_at date NOT NULL,
    reading     numeric(10, 2) NOT NULL
);

INSERT INTO meter_readings
    (reading_id, meter_id, recorded_at, reading)
VALUES
    (1, 101, '2026-05-01', 120.00),
    (2, 101, '2026-05-02', 126.50),
    (3, 101, '2026-05-04', 140.00),
    (4, 202, '2026-05-01',  80.00),
    (5, 202, '2026-05-03',  91.25);

The question is: for each meter and reading, what was the preceding reading for that same meter, and how much did the value change?

Use LAG() in the SELECT list:

SELECT
    reading_id,
    meter_id,
    recorded_at,
    reading,
    LAG(reading) OVER (
        PARTITION BY meter_id
        ORDER BY recorded_at, reading_id
    ) AS previous_reading
FROM meter_readings
ORDER BY meter_id, recorded_at, reading_id;

The query keeps the reading’s ID, meter, date, and value. It adds previous_reading as another result column. For meter 101, the reading on May 2 is compared with the May 1 reading; the May 4 reading is compared with May 2. The missing calendar day does not itself create a row: LAG() looks to a preceding row in the ordered result, not to a preceding date that may not exist.

The diagram summarizes the calculation. PARTITION BY creates separate calculation groups, the window ORDER BY establishes the sequence inside each group, and LAG() supplies the earlier row’s value without replacing the current row.

flowchart LR
    A["Reading rows"] --> B["Partition by meter"]
    B --> C["Order each meter's rows"]
    C --> D["Add prior reading"]
    D --> E["Return detailed rows"]

The outer ORDER BY makes the displayed result follow the same sequence. It is distinct from the ORDER BY inside OVER: the latter defines which row counts as preceding for LAG(), while the outer clause orders the final output.

1. Write the LAG() expression

The basic form is:

LAG(value_expression) OVER (
    PARTITION BY group_expression
    ORDER BY ordering_expression
)

For the readings query, value_expression is reading, the group is meter_id, and the order is recorded_at, reading_id.

LAG(reading) retrieves the value from one preceding row by default. You can also specify how many rows back to look and a value to return when there is no such row:

LAG(value_expression, offset, default_value)

For example, to compare a reading with the value two rows earlier, use an offset of 2:

LAG(reading, 2) OVER (
    PARTITION BY meter_id
    ORDER BY recorded_at, reading_id
) AS reading_two_rows_earlier

This means two preceding rows in the defined order, not two days earlier. If the task is specifically to compare dates separated by two calendar days, a row-offset function alone does not establish that condition; use date-based logic appropriate to that requirement instead.

2. Partition the sequence when rows belong to separate entities

Without PARTITION BY, the window sequence includes rows from the entire query input. That would be wrong for this example: the first row for meter 202 could otherwise be compared with the last row for meter 101.

Keep PARTITION BY meter_id when each meter should have its own history:

SELECT
    meter_id,
    recorded_at,
    reading,
    LAG(reading) OVER (
        PARTITION BY meter_id
        ORDER BY recorded_at, reading_id
    ) AS previous_reading
FROM meter_readings;

Remove PARTITION BY only when the intended sequence really spans all rows. If the actual data is scoped by more than one key—for example, a device within a customer—the partition should reflect the full identity of the sequence:

LAG(reading) OVER (
    PARTITION BY customer_id, device_id
    ORDER BY recorded_at, reading_id
)

Choose partition columns based on the business meaning of “previous.” Two readings from different devices should not be compared merely because their timestamps are adjacent in a combined result.

3. Make the row order deterministic

LAG() needs an order to determine which row precedes the current one. A timestamp is often a sensible first sort key, but timestamps can repeat. If two rows have the same timestamp, add a tie-breaker that distinguishes them, such as a unique ID:

ORDER BY recorded_at, reading_id

The unique key makes the order between same-time rows explicit. If you omit a tie-breaker, the query does not define which tied row is immediately before the other. That can make the previous-row comparison ambiguous for the data you intend to analyze.

The choice of ascending or descending order also changes what “previous” means. With ascending time, LAG() looks to an earlier point in the timeline. With descending time, the preceding row in the window order is later in the timeline. Use the direction that matches the question, and make the final output order clear too.

For example, to display newest readings first while still comparing each reading with the earlier reading in time, keep the window order ascending and reverse only the result order:

SELECT
    reading_id,
    meter_id,
    recorded_at,
    reading,
    LAG(reading) OVER (
        PARTITION BY meter_id
        ORDER BY recorded_at, reading_id
    ) AS previous_reading
FROM meter_readings
ORDER BY meter_id, recorded_at DESC, reading_id DESC;

The calculation’s direction and the screen’s display order are independent decisions. Keep them separate when they serve different purposes.

4. Calculate the difference without losing the original columns

Once the previous value is available, subtract it from the current reading:

SELECT
    reading_id,
    meter_id,
    recorded_at,
    reading,
    LAG(reading) OVER (
        PARTITION BY meter_id
        ORDER BY recorded_at, reading_id
    ) AS previous_reading,
    reading - LAG(reading) OVER (
        PARTITION BY meter_id
        ORDER BY recorded_at, reading_id
    ) AS change_from_previous
FROM meter_readings
ORDER BY meter_id, recorded_at, reading_id;

For meter 101, the May 2 change is 126.50 - 120.00, or 6.50. The May 4 change is 140.00 - 126.50, or 13.50. The first row for each meter has no preceding row within its partition, so there is no previous reading to subtract.

Repeating the window expression is straightforward, but it can be harder to maintain when the expression is more complex. A subquery gives the calculated previous value a name and lets the outer query use it:

SELECT
    reading_id,
    meter_id,
    recorded_at,
    reading,
    previous_reading,
    reading - previous_reading AS change_from_previous
FROM (
    SELECT
        reading_id,
        meter_id,
        recorded_at,
        reading,
        LAG(reading) OVER (
            PARTITION BY meter_id
            ORDER BY recorded_at, reading_id
        ) AS previous_reading
    FROM meter_readings
) AS readings_with_previous
ORDER BY meter_id, recorded_at, reading_id;

This form is useful when the outer query needs several calculations based on the same prior-row value. It also makes the stages visible: first calculate the previous value, then derive the change while retaining the original fields.

5. Decide what the first row should show

By default, a row without a preceding row in its partition gets NULL for the LAG() result. In this example, that applies to the first reading for each meter. Subtracting that NULL also produces NULL, which signals that a comparison was unavailable.

If a different fallback is meaningful for the report, provide the third argument. For example, this query uses zero when no previous reading exists:

SELECT
    meter_id,
    recorded_at,
    reading,
    LAG(reading, 1, 0) OVER (
        PARTITION BY meter_id
        ORDER BY recorded_at, reading_id
    ) AS previous_reading_or_zero
FROM meter_readings
ORDER BY meter_id, recorded_at, reading_id;

A zero fallback changes the meaning of the first row’s calculated difference: it makes that value equal to the first reading itself. That may be appropriate for a particular metric, but it is not the same as saying a previous measurement actually existed. Keep NULL if the distinction between “no predecessor” and “a predecessor with value zero” matters to consumers.

6. Filter results after calculating the window value

A common follow-up is to show only rows where the value changed. Use a subquery to calculate the window value first, then filter in the outer query:

SELECT
    reading_id,
    meter_id,
    recorded_at,
    reading,
    previous_reading,
    reading - previous_reading AS change_from_previous
FROM (
    SELECT
        reading_id,
        meter_id,
        recorded_at,
        reading,
        LAG(reading) OVER (
            PARTITION BY meter_id
            ORDER BY recorded_at, reading_id
        ) AS previous_reading
    FROM meter_readings
) AS compared
WHERE previous_reading IS NOT NULL
  AND reading <> previous_reading
ORDER BY meter_id, recorded_at, reading_id;

This excludes the first row in each meter’s sequence because it has no previous value, and excludes rows whose reading matches the previous one. If you want to preserve first rows, remove the previous_reading IS NOT NULL condition and decide explicitly how you want the no-predecessor case handled.

Filtering the input before the window calculation and filtering the calculated result are not interchangeable in every use case. For instance, if you filter the table to a date range in the inner query, the first in-range row will have no predecessor from before that range. If you need to compare it with the last observation before the range, include that prior row in the window input, then apply the reporting-range filter outside the calculation.

Common mistakes to check

  • Comparing unrelated entities: Partition by the key that defines an independent sequence.
  • Leaving ties unresolved: Add a stable tie-breaker to the window order when timestamps can repeat.
  • Assuming a missing date is a missing row: LAG() compares rows that exist; it does not create daily records.
  • Confusing row offsets with time intervals: An offset of two means two rows back, not two units of time.
  • Treating the first-row NULL as a real value: Choose a fallback only when its meaning is appropriate.
  • Assuming the window order sorts the output: Add a top-level ORDER BY for the displayed rows.
  • Filtering away history too early: Decide whether the window should see rows outside the requested reporting period.

A reusable final query

For the original task—retain every meter-reading detail, show the preceding reading, and calculate the difference—use:

SELECT
    reading_id,
    meter_id,
    recorded_at,
    reading,
    previous_reading,
    reading - previous_reading AS change_from_previous
FROM (
    SELECT
        reading_id,
        meter_id,
        recorded_at,
        reading,
        LAG(reading) OVER (
            PARTITION BY meter_id
            ORDER BY recorded_at, reading_id
        ) AS previous_reading
    FROM meter_readings
) AS readings_with_previous
ORDER BY meter_id, recorded_at, reading_id;

The essential decisions are the value to retrieve, the partition that defines an independent history, and the ordering that defines “previous.” With those decisions explicit, LAG() adds a comparison to each detailed row instead of summarizing away the data you need to inspect.

External Sources used for this article

Related Articles

View all →

Put it into practice

Related tools

All tools →