Function or operator · Advanced SQL

FIRST_VALUE and LAST_VALUE in SQL

FIRST_VALUE and LAST_VALUE return the value from the first and last rows of the window frame. To cover the whole partition, declare the full frame.

Before continuing: This entry is part of the window functions guide. If you are new to the topic, start with OVER.

Example

Orders from two customers
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;
Result verified in SQLite 3.46.1
idcustomer_iddatefirst_datelast_date
10112025-05-022025-05-022025-06-01
10312025-05-102025-05-022025-06-01
11112025-06-012025-05-022025-06-01
10432025-05-112025-05-112025-06-12
10732025-05-202025-05-112025-06-12
11632025-06-122025-05-112025-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

Ambiguous for the intent «the customer's last value»
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.