Bird
0
0

Consider this query:

medium📝 Debug Q7 of 15
PostgreSQL - Window Functions in PostgreSQL
Consider this query:
SELECT emp_id, LAST_VALUE(salary) OVER (ORDER BY emp_id) FROM employees;

Why might this query not return the expected last salary value for each employee?
ABecause the query lacks a PARTITION BY clause
BBecause the default window frame ends at the current row, so LAST_VALUE returns the current row's salary
CBecause LAST_VALUE requires a GROUP BY clause to work correctly
DBecause salary is not indexed
Step-by-Step Solution
Solution:
  1. Step 1: Understand window frame default

    By default, the window frame for ORDER BY is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.
  2. Step 2: Effect on LAST_VALUE

    This means LAST_VALUE returns the value of the current row, not the last row in the partition.
  3. Step 3: Correct usage

    To get the actual last value, specify the frame as ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.
  4. Final Answer:

    Because the default window frame ends at the current row, so LAST_VALUE returns the current row's salary -> Option B
  5. Quick Check:

    Check window frame boundaries for LAST_VALUE [OK]
Quick Trick: LAST_VALUE needs full frame to get true last value [OK]
Common Mistakes:
  • Assuming LAST_VALUE returns last row without frame adjustment
  • Ignoring window frame clauses in window functions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes