SQL Window Functions and Cohort Retention
A practical guide to PostgreSQL window functions: defining windows, ranking grouped rows, comparing ordered records, and calculating cohort retention.
Define windows and rank rows within groups
Define a window before ranking
A window function calculates a value across related rows while keeping each row in the result. This differs from GROUP BY, which combines rows into groups and returns grouped results. The clause specifies the window: divides rows into groups, ORDER BY sets their sequence for the calculation, and an optional frame selects a subset of rows for frame-based calculations.
In the employee example, the window is reset for each department and employees are ordered from highest to lowest salary. A common table expression (), declared with WITH, gives the calculation a name; the outer query can then filter its calculated ranks.
WITH ranked AS (
SELECT
employee_id,
department,
salary,
RANK() OVER (
PARTITION BY department
ORDER BY salary DESC
) AS salary_rank,
DENSE_RANK() OVER (
PARTITION BY department
ORDER BY salary DESC
) AS salary_dense_rank,
ROW_NUMBER() OVER (
PARTITION BY department
ORDER BY salary DESC, employee_id
) AS position
FROM employees
)
SELECT employee_id, department, salary, salary_rank, salary_dense_rank, position
FROM ranked
WHERE salary_rank <= 3
ORDER BY department, salary DESC, employee_id;
The three ranking functions answer slightly different questions. RANK() gives tied rows the same rank and leaves a gap afterward. DENSE_RANK() also gives ties the same rank, but does not leave a gap. ROW_NUMBER() assigns each row a unique sequence number; adding employee_id as a stable tie-breaker makes the order deterministic when salaries match.
For illustration, suppose one department has salaries ordered as 120, 100, 100, and 90. The first two ranking functions assign ranks 1, 2, 2, 4 and dense ranks 1, 2, 2, 3; ROW_NUMBER() assigns 1, 2, 3, 4, with the employee ID deciding the order of the two tied salaries. Here, salary_rank <= 3 includes both employees tied at rank 2, while position <= 3 would return exactly three rows. More generally, filtering RANK() <= 3 includes everyone tied at rank 3, whereas filtering ROW_NUMBER() <= 3 returns at most three rows per department.
Rows tied on every expression in a window's ORDER BY are peers. Also distinguish that ordering from the query's final ordering: the window's ORDER BY controls the calculation, not how the result is displayed. The outer ORDER BY in the example sorts the output by department, salary, and employee ID.
Compare neighboring rows and calculate rolling averages
Compare neighboring rows and calculate a rolling average
accesses a previous row in the ordered partition; LEAD() accesses a following row. In the monthly-amount example, partitioning by account keeps accounts separate, and ordering by month determines which row counts as previous. Subtracting the previous amount from the current amount gives the change from that row:
SELECT
account_id,
month,
amount,
amount - LAG(amount) OVER (
PARTITION BY account_id
ORDER BY month
) AS change_from_previous_row,
AVG(amount) OVER (
PARTITION BY account_id
ORDER BY month
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) AS rolling_avg_3_rows
FROM monthly_amounts
ORDER BY account_id, month;
For each row, amount - LAG(amount) compares its amount with the preceding month-ordered row for the same account. If a month is missing, that preceding row is not necessarily from the immediately preceding calendar month. An aggregate such as AVG() can also be used as a window function, so the query calculates an average without collapsing the monthly rows.
The explicit frame ROWS BETWEEN 2 PRECEDING AND CURRENT ROW includes the current row and up to two earlier rows: at most three rows in total. Near the start of a partition, fewer than three rows are available, so the average uses those available rows. This is not necessarily an average three calendar months. If some months are missing, the three rows may span a longer period.
For an ordered aggregate window, the default frame generally produces a running result through the current row and its peers. Specify a frame deliberately when you want a particular rolling window. Finally, the window's ORDER BY month determines the calculation's sequence; the outer ORDER BY account_id, month controls the order in which results are displayed.
Build a -retention calculation
Build a -retention calculation
A groups users by the month they first appeared. To calculate retention, first find each user's earliest recorded event, assign that user a month, and count the original size. Then count each user's activity at most once per month, tally active users for each and activity month, and compare that count with the 's original size.
The PostgreSQL query below assumes user_events(user_id, event_at) records activity and that multiple events by one user in the same month count as one active user. Its CTEs separate these steps:
WITH first_seen AS (
SELECT user_id, MIN(event_at) AS first_event_at
FROM user_events
GROUP BY user_id
), cohorts AS (
SELECT user_id, DATE_TRUNC('month', first_event_at) AS cohort_month
FROM first_seen
), cohort_sizes AS (
SELECT cohort_month, COUNT(*) AS cohort_size
FROM cohorts
GROUP BY cohort_month
), user_months AS (
SELECT DISTINCT user_id, DATE_TRUNC('month', event_at) AS activity_month
FROM user_events
), retained AS (
SELECT
c.cohort_month,
u.activity_month,
COUNT(*) AS active_users
FROM cohorts AS c
JOIN user_months AS u USING (user_id)
GROUP BY c.cohort_month, u.activity_month
)
SELECT
r.cohort_month,
r.activity_month,
(
(EXTRACT(YEAR FROM r.activity_month) - EXTRACT(YEAR FROM r.cohort_month)) * 12
+ EXTRACT(MONTH FROM r.activity_month) - EXTRACT(MONTH FROM r.cohort_month)
) AS months_after_cohort,
r.active_users,
ROUND(100.0 * r.active_users / s.cohort_size, 1) AS retention_percent
FROM retained AS r
JOIN cohort_sizes AS s USING (cohort_month)
ORDER BY r.cohort_month, r.activity_month;
first_seen uses each user's minimum event timestamp; cohorts truncates it to a month. Since first_seen has one row per user, cohort_sizes counts the original users in each . user_months uses DISTINCT after truncating event times to months, so repeated events by the same user in one month contribute only one user-month. Joining those activity months to the users' cohorts lets retained count active users for each -month and activity-month pair.
The elapsed-month calculation compares year differences multiplied by 12, then adds the difference in month numbers. This handles changes across years as well as within a year. Retention is calculated as:
The final query rounds the percentage to one decimal place and orders results by month and activity month. Because it starts from recorded activity, it returns months with activity, not -month pairs with zero active users. To display zero-activity months too, generate a calendar of -month pairs and left join the activity counts.
: A specified set of rows used for a frame-based window calculation.