Question presented to candidate: "What do LAG and LEAD do? Say I have monthly revenue and I want each month next to the previous month and the change between them β how would you write it, and what happens on the first row?"
What a strong answer should cover:
LAG(expr)returnsexprfrom the row before the current one in the window order,LEAD(expr)from the row after; both keep every row and replace a self join on "the previous row"- Full form
LAG(expr, offset, default): offset is how many rows back (default 1), default is returned when that row does not exist (otherwise NULL, so the first row has no previous value) - They need
ORDER BYinOVERto mean anything, andPARTITION BYto stop one entity (a user) reading another entity rows - Typical uses: period-over-period change, time between events per user, detecting state changes; filter on the result in an outer query
- Gotchas: integer division in percentage change, the default must match the column type on PostgreSQL, and
IGNORE NULLSis not available on PostgreSQL 16 or SQLite (SQL Server 2022 has it)
Code / implementation expected: Yes β previous and next value with the difference, plus a per-user version with PARTITION BY.
Schema used by the examples: