Window Functions
First and Last Values in a Window
Senior Data Analyst
March 6, 2026
5 min read
The First Order Problem
For each customer, I wanted to show every order alongside the date of their *first-ever* order.
The Functions
The Syntax
SELECT
customer_id, order_date, amount,
FIRST_VALUE(order_date) OVER (PARTITION BY customer_id ORDER BY order_date) AS first_order_date
FROM orders;
Pro Tip
`LAST_VALUE` often returns the current row's value because the default frame ends at the current row. To get the true last value:
LAST_VALUE(amount) OVER (
PARTITION BY customer_id ORDER BY order_date
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
)
*Day 66: NTILE—Dividing Data into Buckets.*