Explain the FIRST_VALUE() and LAST_VALUE() functions. Why does LAST_VALUE() often return unexpected results unless you specify an explicit frame?
Last updated
FIRST_VALUE()andLAST_VALUE()are window functions that return the first and last row's value in the window frame (the rows the function sees).With
ORDER BYand no explicit frame, the frame ends at the current row. SoLAST_VALUE()returns the current row's value, whileFIRST_VALUE()looks correct only because the frame always starts at the partition start.Fix it with
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWINGso the frame covers the whole partition.