Before continuing: This entry is part of the window functions guide. If you are new to the topic, start with OVER.
Example
SELECT
id,
customer_id,
date,
FIRST_VALUE(date) OVER (
PARTITION BY customer_id
ORDER BY date, id
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS first_date,
LAST_VALUE(date) OVER (
PARTITION BY customer_id
ORDER BY date, id
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS last_date
FROM orders
WHERE customer_id IN (1, 3)
ORDER BY customer_id, date, id;| id | customer_id | date | first_date | last_date |
|---|---|---|---|---|
| 101 | 1 | 2025-05-02 | 2025-05-02 | 2025-06-01 |
| 103 | 1 | 2025-05-10 | 2025-05-02 | 2025-06-01 |
| 111 | 1 | 2025-06-01 | 2025-05-02 | 2025-06-01 |
| 104 | 3 | 2025-05-11 | 2025-05-11 | 2025-06-12 |
| 107 | 3 | 2025-05-20 | 2025-05-11 | 2025-06-12 |
| 116 | 3 | 2025-06-12 | 2025-05-11 | 2025-06-12 |
All six rows are still in the result. What repeats within each customer are the calculated first and last dates.
How it is used
These functions neither remove rows nor replace MIN() or MAX(). The question is not «what is the earliest date?» but «once each customer's rows are sorted, what value does the first or last row of that sequence hold?».
That lets you show, next to each order, the same customer's first and last purchase dates. The detail stays visible because window functions calculate one value per row.
What changes from case to case
The detail that usually trips up LAST_VALUE: the window frame
With a ORDER BY, several engines default to a frame that ends at the current row or its peers. In that case, LAST_VALUE() can return the current row's value instead of the last value in the whole partition.
Assuming LAST_VALUE always looks to the end
LAST_VALUE(date) OVER (
PARTITION BY customer_id
ORDER BY date, id
)If you need the last value in the whole partition, declare the full frame explicitly with ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.
When to use these functions
- First or last date: the start and end of a sequence per customer, employee or product.
- First or last status: when the order in time describes how something evolved and you want to keep every event.
- Reference value: compare each row with the first or last value of the same group.
If you only need one row per group, an aggregate or a top N per group pattern may be more direct. If you need to keep every row, window functions are the natural tool.