๐Ÿง  FIRST_VALUE(): Get the First Row in a Group

Xorthax can now look backward and forward between rows. But sometimes he wants something simpler:

What is the first value in this group?

That's what FIRST_VALUE() does.




๐Ÿš€ FIRST_VALUE() + OVER()

FIRST_VALUE() returns the first value in a sequence of rows.

FIRST_VALUE(column) OVER (
  PARTITION BY column
  ORDER BY column
)

Hereโ€™s why:

  • PARTITION BY defines the group
  • ORDER BY defines which row is first



๐Ÿ“Š Example: First 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,
       FIRST_VALUE(Amount) OVER (
         PARTITION BY CustomerID
         ORDER BY OrderDate
       ) AS FirstAmount
FROM Orders;

Result:

CustomerID OrderDate Amount FirstAmount
A2024-01-01100100
A2024-01-05150100
B2024-01-02200200
B2024-01-0650200

Each row now shows the first 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.

FIRST_VALUE() looks at the first row in that ordered sequence.

That value is then repeated for every row in the group.

If you change the order, you change what counts as first. And you must have an ORDER BY so SQL knows what is first!




๐Ÿงช Practice What You Just Learned

First Order Amount

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


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



โžก๏ธ Next Step

FIRST_VALUE() gives you the beginning of a sequence.

Next, you'll learn how to get the value at the end.




Want to go deeper?