SQL FIRST_VALUE() and LAST_VALUE(): why LAST_VALUE() needs an explicit window frame

Quick Overview

Asks what the SQL window functions FIRST_VALUE() and LAST_VALUE() return and why LAST_VALUE() surprises people when no frame clause is given. Tests understanding of default window frames, ROWS versus RANGE, ties in the ORDER BY, and how to write a frame that covers the whole partition.

SQL FIRST_VALUE() and LAST_VALUE(): why LAST_VALUE() needs an explicit window frame

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: medium

Interview Round: Other

Explain the `FIRST_VALUE()` and `LAST_VALUE()` window functions. Why does `LAST_VALUE()` often return unexpected results unless you specify an explicit frame? ```hint List the visible rows For each row, write out which rows the window function can see when the window has an `ORDER BY` but no frame clause. ``` ```hint Watch for ties Then check what changes when two rows share the same `ORDER BY` value. ``` ### What a Strong Answer Covers - What each function returns, and how the window frame defines "first" and "last". - The default frame when `ORDER BY` is present, and how it limits what `LAST_VALUE()` can reach. - Why `FIRST_VALUE()` does not show the same problem. - How to write the fix, and other queries that give the same result. - How ties in the `ORDER BY` affect the result. ### Follow-up Questions - How does the default frame change if you remove `ORDER BY` from the window? - What is the difference between a `ROWS` frame and a `RANGE` frame when the ordering column has duplicates? - How would you get the last non-null value of a column within each partition? - Does `NTH_VALUE()` have the same problem?

Overview: Asks what the SQL window functions FIRST_VALUE() and LAST_VALUE() return and why LAST_VALUE() surprises people when no frame clause is given. Tests understanding of default window frames, ROWS versus RANGE, ties in the ORDER BY, and how to write a frame that covers the whole partition.

Nov 24, 2026
mediumData ScientistOtherData Manipulation (SQL/Python)
0
0

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

What a Strong Answer Covers Guidance

  • What each function returns, and how the window frame defines "first" and "last".
  • The default frame when ORDER BY is present, and how it limits what LAST_VALUE() can reach.
  • Why FIRST_VALUE() does not show the same problem.
  • How to write the fix, and other queries that give the same result.
  • How ties in the ORDER BY affect the result.

Follow-up Questions Guidance

  • How does the default frame change if you remove ORDER BY from the window?
  • What is the difference between a ROWS frame and a RANGE frame when the ordering column has duplicates?
  • How would you get the last non-null value of a column within each partition?
  • Does NTH_VALUE() have the same problem?