SQL NTH_VALUE

Returns the value from a specific position in the window — and has the exact same frame gotcha as LAST_VALUE.

What & Why

NTH_VALUE(column, n) returns the value from the nth row of the window. Like LAST_VALUE, it's affected by the frame — asking for a position past where the default frame currently ends returns NULL until the frame catches up.

See How It Works

BUSINESS QUESTION

Growth shows the third recorded DAU value beside every daily row.

date_daydaunew_usersreturning_users
2024-04-0112401801060
2024-04-0213152051110
2024-04-0312881641124
2024-04-0413922211171
EXAMPLE QUERY
SELECT
  date_day,
  dau,
  NTH_VALUE(dau, 3) OVER (
    ORDER BY date_day
    ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
  ) AS third_day_dau
FROM growth.daily_active_users
ORDER BY date_day;
RESULT — third recorded DAU
date_daydauthird_day_dau
2024-04-0112401288
2024-04-0213151288
2024-04-0312881288
2024-04-0413921288

The third row in date order contains DAU 1,288.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario