Knowledge base / SQL

LAST_VALUE in PostgreSQL: the last value depends on the frame

I compare a customer's final value with the current row and show why a correct ORDER BY still needs the appropriate window frame.

Kajo RudzińskiPublished Updated 5 min read

A frame encloses a sequence of blocks while a light highlights the last block rather than the tallest.

I want every order to display the amount of its customer’s final order. I write LAST_VALUE, add sorting and receive something very close to a copy of the current amount. The function answered a different question because the frame ended too early. I therefore start with three decisions: whose rows, in which order and across which range?

This entry concerns PostgreSQL 18. The data is synthetic. Here, last means the greatest order date, with ID as an agreed tiebreaker. In an actual system, establish whether ID fits the intended rule. Do not automatically equate it with event time or assume every identifier reflects chronology.

The entire partition: a final-order example

LAST_VALUE returns the value from the last frame row. I explicitly extend the frame from the beginning to the end of the partition. PARTITION BY separates customers, while ORDER BY establishes their order sequence.

WITH orders(id, customer, order_day, amount) AS (
    VALUES
        (1, 'A', DATE '2026-11-01', 100),
        (2, 'A', DATE '2026-11-02', 300),
        (3, 'A', DATE '2026-11-03', 200),
        (4, 'B', DATE '2026-11-01', 500),
        (5, 'B', DATE '2026-11-02', 400)
)
SELECT id, customer, amount,
       LAST_VALUE(amount) OVER (
           PARTITION BY customer
           ORDER BY order_day, id
           ROWS BETWEEN UNBOUNDED PRECEDING
                    AND UNBOUNDED FOLLOWING
       ) AS last_amount
FROM orders
ORDER BY customer, order_day, id;
id customer amount last_amount
1 A 100 200
2 A 300 200
3 A 200 200
4 B 500 400
5 B 400 400

For A, ID 3 is last, so every A row receives 200. For B, ID 5 is last, giving 400. The original order rows remain separate. A window function does not reduce this result to one record per customer. That matters when the recipient needs both the individual order and a value describing its surrounding history.

The largest amount deliberately appears before the end. A’s maximum is 300, while its final amount is 200. B’s maximum is 500, while its final amount is 400. Replacing the function with MAX(amount) would therefore change the question. The two answers can happen to agree on another dataset without making the operations interchangeable.

CURRENT ROW defines a different range

Using the same data, replace only the frame with:

ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW

The last frame row is now the current row. The successive results are 100, 300, 200, 500 and 400. That correctly answers the question implied by this frame, but does not describe the end of each customer’s history. The earlier Polish entry used this range in its main example despite asking about the final order.

If you want information available at the moment of each order, UNBOUNDED FOLLOWING may itself be inappropriate: earlier rows can see later events. Historical reporting needs an explicit information boundary. Last in the entire selected dataset and last known at that time are different requirements. Choose the frame using that distinction instead of treating the full partition as an automatic correction for every use of the function.

The default frame includes peers

With ORDER BY and no explicit frame, the default is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. In RANGE mode, the end at CURRENT ROW reaches the last peer under the window ordering. This is a PostgreSQL framing rule, rather than a guarantee that the frame stops at the individual current record.

Our main ordering uses a unique order_day, id pair. The default frame therefore ends at that specific order. If you sort only by date, two orders on the same date become peers. Without another rule, you have not specified which should be last. Extending the frame to the entire partition does not resolve an ambiguous ordering by itself. Frame boundaries and tiebreaking are separate decisions.

Without ORDER BY, the default frame covers the partition, but unspecified ordering cannot guarantee a meaningful final order. I do not rely on insertion order or the way a database viewer displays the table. The rule should be part of the query and match the business requirement. Otherwise a plausible-looking answer may depend on circumstances the query never promised to preserve.

A short frame ends at one block while a longer frame encloses the complete ordered sequence.

A final NULL remains NULL

Change order 3’s amount from 200 to NULL. With the full frame, every A row receives NULL because that is the evaluated column’s value in the final row. The function does not automatically return the preceding 300. PostgreSQL 18 does not implement IGNORE NULLS; its behaviour respects NULL values.

If the requirement is the last known amount, design a different selection rule. First establish what the missing value means: an unknown amount, another event type or an import error. Skipping the record automatically could conceal useful information. Here I retain the function’s explicit behaviour rather than presenting COALESCE with zero as a solution to an ordering problem. A replacement value cannot identify which historical row you intended to select.

Filtering changes the history visible to the window

Window functions operate on rows remaining after earlier query stages, including WHERE, as explained in the PostgreSQL tutorial. Limit the input to 1 November before calculation and A receives 100 while B receives 500. Those are the final amounts within that restricted dataset, rather than within the full sample history.

If you need to calculate across the full history and only then display selected rows, separate the stages with a subquery or CTE. Keep the purpose in mind: for an as-of analysis, access to future history would leak information. An outer filter and an inner filter can both be valid while answering different questions. I would not move the condition mechanically just to obtain a number I expected to see.

Exercise: check the final-record rule

Add an order for A with a later date and an amount of 50. With the full frame, every A row should show 50, while the maximum remains 300. Replace that amount with NULL and explain the change. Finally, introduce a date tie and specify how you want it resolved. The exercise separates the selected value, the sort order and the frame rather than changing all three at once.

Before using the function, document the partition unit, complete ordering, frame and data boundary. The guide to SQL clause order helps explain filtering, while the SQL knowledge base links related window functions. A clear alias such as last_amount helps readability, but cannot replace those four decisions.

Key takeaways

Why does LAST_VALUE return the current row's value?

The frame may end at the current row. With unique ordering, the default ORDER BY frame has that effect too. Use UNBOUNDED FOLLOWING for the final value across the partition.

Is LAST_VALUE equivalent to MAX?

No. LAST_VALUE selects the value from the final frame row under the specified ordering. MAX selects the greatest value, irrespective of chronology.

Does PostgreSQL 18 support IGNORE NULLS for LAST_VALUE?

No. PostgreSQL 18 respects NULL. If the evaluated column is NULL in the last frame row, the result is NULL.

AI was used in an automated way while working on this article. If you want to learn how to do it too, check out this project.

Kajo Rudziński

Newsletter KajoData

Let’s keep in touch.

I write about data analysis, learning and changing careers. My newsletter and the sign-up form are in Polish. If that works for you, I’d be glad to see you there.