Explain the FIRST_VALUE() and LAST_VALUE() functions. Why does LAST_VALUE() often return unexpected results unless you specify an explicit frame?

Last updated 13 July 2026

  • FIRST_VALUE() and LAST_VALUE() are window functions that return the first and last row's value in the window frame (the rows the function sees).

  • With ORDER BY and no explicit frame, the frame ends at the current row. So LAST_VALUE() returns the current row's value, while FIRST_VALUE() looks correct only because the frame always starts at the partition start.

  • Fix it with ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING so the frame covers the whole partition.

  • https://dev.to/dishon_gatambiadd_31a1/sql-analytical-mechanics-joins-window-functions-pc4
  • https://reintech.io/blog/mastering-sql-first-value-last-value-functions
All Advanced SQL interview questions