Part 07 / Topic 4 of 8
FIRST_VALUE and LAST_VALUE
FIRST_VALUE(col) gives the first value in the window; LAST_VALUE(col) the last. Except, famously, it doesn't seem to:
SELECT name, price,
FIRST_VALUE(name) OVER (ORDER BY price DESC) AS priciest,
LAST_VALUE(name) OVER (ORDER BY price DESC) AS cheapest_maybe
FROM products
WHERE category_id IN (4, 5)
ORDER BY price DESC;
name | price | priciest | cheapest_maybe
---------------+---------+---------------+----------------
Laptop Pro 14 | 1200.00 | Laptop Pro 14 | Laptop Pro 14
Laptop Air 13 | 950.00 | Laptop Pro 14 | Laptop Air 13
Phone X | 799.00 | Laptop Pro 14 | Phone X
Phone Lite | 399.00 | Laptop Pro 14 | Phone Lite
(4 rows)
priciest is right; cheapest_maybe just echoes each row's own name. The reason is the default frame: with an ORDER BY, a window function sees only from the partition's start to the current row — so the "last" value is always the current one. Widen the frame and LAST_VALUE behaves:
SELECT name, price,
LAST_VALUE(name) OVER (ORDER BY price DESC
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS cheapest
FROM products
WHERE category_id IN (4, 5)
ORDER BY price DESC;
name | price | cheapest
---------------+---------+------------
Laptop Pro 14 | 1200.00 | Phone Lite
Laptop Air 13 | 950.00 | Phone Lite
Phone X | 799.00 | Phone Lite
Phone Lite | 399.00 | Phone Lite
(4 rows)
(That ROWS BETWEEN ... is a frame — section 6 explains the machinery. In practice: FIRST_VALUE works as expected; for "last", either fix the frame or flip the ORDER BY and use FIRST_VALUE.)
🧪 Quick quiz — answer from memory, then check.
LAST_VALUE(x) OVER (ORDER BY x)over 1, 2, 3 returns…?- Why?
Show the answers
- 1, 2, 3 — each row's own value, not three 3s.
- The default frame ends at the current row, so the "last" visible value is the current one. Extend the frame to UNBOUNDED FOLLOWING for the real last.
Exercise 4: Revenue, accumulating
What to do: Monthly delivered revenue with a running total — CTE for the months, window for the accumulation.
Sample output:
month | revenue | running_total
------------+---------+---------------
2025-01-01 | 2069.00 | 2069.00
2025-02-01 | 135.00 | 2204.00
2025-03-01 | 150.00 | 2354.00
2025-04-01 | 1709.00 | 4063.00
(4 rows)
💡 Hint: sum(revenue) OVER (ORDER BY month).
Show the solution to Exercise 4
-- Exercise 4: Revenue, accumulating
WITH monthly AS (
SELECT date_trunc('month', o.order_date)::date AS month,
sum(oi.quantity * oi.unit_price) AS revenue
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status = 'delivered'
GROUP BY 1
)
SELECT month, revenue,
sum(revenue) OVER (ORDER BY month) AS running_total
FROM monthly
ORDER BY month;