FIRST_VALUE vs LAST_VALUE in SQL (Avoid This Common Window Function Trap)
After RANK, DENSE_RANK, ROW_NUMBER, LEAD, and LAG, the next underrated but powerful SQL window functions are
π FIRST_VALUE() and LAST_VALUE().
They look simpleβbut many people get wrong results in interviews and real projects due to misunderstanding window frames.
Letβs clear that confusion once and for all.
π§ Problem Statement
π From a sales table, find:
- First sale amount
- Latest sale amount
for each product.
Sample data:
| product | sale_date | amount |
|---|---|---|
| A | 2023-01-01 | 100 |
| A | 2023-02-01 | 150 |
| A | 2023-03-01 | 200 |
π₯ Using FIRST_VALUE()
SELECT product,
sale_date,
amount,
FIRST_VALUE(amount) OVER (
PARTITION BY product
ORDER BY sale_date
) AS first_sale
FROM sales;
β What it does
- Returns the first value in the ordered window
- Works as expected without extra configuration
Result for product A:
- First sale = 100 for all rows
β οΈ The Trap with LAST_VALUE()
SELECT product,
sale_date,
amount,
LAST_VALUE(amount) OVER (
PARTITION BY product
ORDER BY sale_date
) AS last_sale
FROM sales;
β Surprise result!
Instead of returning 200, this query returns the current rowβs amount.
Why?
π Because by default, SQL considers the window frame as:
RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
So LAST_VALUE() stops at the current row, not the actual last row.
β
Correct Way to Use LAST_VALUE()
SELECT product,
sale_date,
amount,
LAST_VALUE(amount) OVER (
PARTITION BY product
ORDER BY sale_date
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS last_sale
FROM sales;
β Now it works correctly:
- Last sale = 200 for all rows of product A
π Key Difference (Interview Favorite)
| Function | Default behavior |
|---|---|
| FIRST_VALUE() | Works as expected |
| LAST_VALUE() | Needs explicit window frame |
π Always define the window frame when using LAST_VALUE().
π‘ Real-World Use Cases
- First vs latest transaction
- Opening vs closing balance
- First login vs last login
- Initial vs final price comparison
π¬ Interview Question for You
How would you calculate the price difference between first and last transaction per product using window functions only?
(Hint: Combine FIRST_VALUE() and LAST_VALUE() π)
Comments (0)
No comments yet. Be the first to share your thoughts!
Leave a Comment