๐Ÿง  LAST_VALUE(): Get the Last Row in a Group

Xorthax now knows how to get the first value in a group. But what if he wants the value at the end?

That's what LAST_VALUE() does - but it requires one important detail.




๐Ÿš€ LAST_VALUE() + OVER()

LAST_VALUE() returns the last value in a sequence of rows.

LAST_VALUE(column) OVER (
  PARTITION BY column
  ORDER BY column
  ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
)

This works because:

  • PARTITION BY defines the group
  • ORDER BY defines the sequence
  • The frame includes all rows in the group



๐Ÿ“Š Example: Last Order Amount per Customer

๐Ÿงพ Sample Data

CustomerID OrderDate Amount
A2024-01-01100
A2024-01-05150
B2024-01-02200
B2024-01-0650

SELECT CustomerID, OrderDate, Amount,
       LAST_VALUE(Amount) OVER (
         PARTITION BY CustomerID
         ORDER BY OrderDate
         ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
       ) AS LastAmount
FROM Orders;

Result:

CustomerID OrderDate Amount LastAmount
A2024-01-01100150
A2024-01-05150150
B2024-01-0220050
B2024-01-065050

Each row now shows the last value within its customer group.




What's Happening Here?

PARTITION BY CustomerID creates a group for each customer.

ORDER BY OrderDate defines the sequence within each group.

The window frame includes all rows in the group, so LAST_VALUE() can see the true last row.


Important: If you leave out the window frame, SQL only looks at rows up to the current row.

That means LAST_VALUE() will return the current row's valueโ€”not the actual last value in the group.




๐Ÿงช Practice What You Just Learned

Last Order Amount

For each order, show the totalamount from the last order based on orderdate.


Tables Used
orders
ColumnType
orderidbigint
customeridbigint
orderdatetimestamp without time zone
totalamountdouble precision
statustext
Expected Output
Column
orderid
orderdate
totalamount
last_amount
Write Your Query:



โžก๏ธ Next Step

FIRST_VALUE() and LAST_VALUE() give you the edges of a sequence.

Next, you'll learn how to get a value from any position.




Want to go deeper?