Learn SQL/Advanced/Window Functions/SQL Window Functions

SQL Window Functions

Compute across a group of rows — without collapsing them the way GROUP BY does.

What & Why

A window function calculates across related rows while preserving every input row in the output. Windows add group context to row-level data, which is essential for ranking, running totals, and period comparisons.

See How It Works

BUSINESS QUESTION

Rank each user by signup recency within their country.

idcreated_atcountrychannelplanactivated_atchurned_at
1012024-01-15 09:10:00+00USorganicpro2024-01-16 14:25:00+00NULL
1022024-02-10 11:05:00+00CApaidfreeNULL2024-03-20 10:00:00+00
1032024-03-12 16:35:00+00GBreferralpro2024-03-13 08:15:00+00NULL
1042024-04-01 13:20:00+00USorganicfree2024-04-03 12:00:00+00NULL
EXAMPLE QUERY
SELECT
  id,
  country,
  created_at,
  ROW_NUMBER() OVER (
    PARTITION BY country
    ORDER BY created_at DESC, id
  ) AS country_signup_rank
FROM growth.users
ORDER BY country, country_signup_rank;
RESULT — signup rank within country
idcountrycreated_atcountry_signup_rank
102CA2024-02-10 11:05:00+001
103GB2024-03-12 16:35:00+001
104US2024-04-01 13:20:00+001
101US2024-01-15 09:10:00+002

ROW_NUMBER restarts for each country while preserving every user row.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario