Most tutorials on SQL window functions use student test scores or employee salaries. Then you sit down to build a revenue dashboard and have to translate everything. This guide skips that step. Every example is a metric someone in a business actually asks for, built on small Stripe and Shopify style tables, with the input and the output shown so you can check each step.

The short version. You write a window function as function() OVER (PARTITION BY ... ORDER BY ... frame). With five of them you can build most of a metrics layer: ROW_NUMBER for "first" and "latest", LAG for growth rates, SUM with a frame for running totals, AVG with a frame for moving averages, and FIRST_VALUE for cohort retention.

Which window function answers which question

The questionWindow functionWhere
What did each customer buy first? Which record is the latest?ROW_NUMBER() with QUALIFYSection 1
Who are the top 3 customers, ties included?RANK() or DENSE_RANK()Section 1
How much did revenue grow month over month?LAG()Section 2
How many days until a customer orders again?LEAD()Section 2
What is MRR at the end of each month?SUM() OVER (ORDER BY ...)Section 3
What share of revenue does each customer bring?SUM() OVER ()Section 3
What is the 7 day average, without the daily noise?AVG() OVER (ROWS BETWEEN ...)Section 4
How many customers come back after their first month?MIN() OVER and FIRST_VALUE()Section 5

The examples are written for DuckDB, whose syntax is close to Snowflake's and PostgreSQL's, and each was run against the sample tables shown with it. Where BigQuery, Snowflake or PostgreSQL need different syntax, the section gives that version (the PostgreSQL ones were run on PostgreSQL 16), and there is a full syntax table near the end.

What SQL window functions do, in one picture

SQL window functions calculate a value for each row from a set of related rows, called the window, and keep every row in the result. An aggregate with GROUP BY collapses each group into one row; a window function such as SUM(...) OVER (PARTITION BY ...) returns the same total next to every row instead. That makes running totals, rankings and period over period comparisons possible in one query.

Start with nine Shopify orders from four customers:

order_idcustomer_idcreated_attotal_price
1001c_anna2026-01-04 09:12120.00
1002c_ben2026-01-09 14:3080.00
1003c_anna2026-02-02 11:0560.00
1004c_cara2026-02-14 16:45200.00
1005c_ben2026-03-03 10:2095.00
1006c_anna2026-03-21 18:0040.00
1007c_dev2026-03-25 12:10150.00
1008c_cara2026-04-08 08:55110.00
1009c_dev2026-04-19 19:4070.00

If you want revenue per customer, GROUP BY gives you one row per customer and the orders disappear. Often that is what you want. But just as often you want both: every order, plus a number computed across that customer's orders. That is what a window function does.

How SQL window functions differ from GROUP BY, on nine Shopify orders from four customers. GROUP BY customer_id collapses the nine rows into four, one total per customer: Anna 220, Ben 175, Cara 310, Dev 220. A window function keeps all nine rows. SUM OVER PARTITION BY customer_id repeats each customer's total on every one of their orders, and adding ORDER BY created_at turns it into a running total per customer, for example 120, 180, 220 for Anna.
SQL
1select
2    order_id,
3    customer_id,
4    total_price,
5    sum(total_price) over (
6        partition by customer_id
7    ) as customer_revenue,
8    sum(total_price) over (
9        partition by customer_id
10        order by created_at
11    ) as running_revenue
12from orders
13order by customer_id, created_at;
order_idcustomer_idtotal_pricecustomer_revenuerunning_revenue
1001c_anna120.00220.00120.00
1003c_anna60.00220.00180.00
1006c_anna40.00220.00220.00
1002c_ben80.00175.0080.00
1005c_ben95.00175.00175.00
1004c_cara200.00310.00200.00
1008c_cara110.00310.00310.00
1007c_dev150.00220.00150.00
1009c_dev70.00220.00220.00

The three parts of OVER (...) each answer one question:

  • PARTITION BY: which rows belong together? Here, one customer's orders. Without it, the whole table is one partition.
  • ORDER BY: in what order? It is what turns a total into a running total, and it decides what "first" and "previous" mean for ROW_NUMBER, LAG and LEAD. Snowflake rejects those three without it and BigQuery rejects LAG and LEAD; PostgreSQL runs them, but the order is then arbitrary.
  • The frame: which of those rows go into this row's result? You rarely see it because there is a default, but it decides every running total and moving average. Section 4 covers it.

Window functions run after WHERE, GROUP BY and HAVING, and before the final ORDER BY and LIMIT. Two consequences come up all the time: you can put a window around an aggregate (sum(sum(x)) over (...), used below for MRR), and you cannot filter on a window function in WHERE. That second one is what QUALIFY is for.

1. First order per customer: ROW_NUMBER, RANK and QUALIFY

"What did each customer buy first?" drives first order AOV, acquisition channel reports and every "new vs returning" split. ROW_NUMBER() numbers the rows inside each partition in the order you give it:

SQL
1select
2    order_id,
3    customer_id,
4    created_at,
5    row_number() over (
6        partition by customer_id
7        order by created_at
8    ) as order_number
9from orders
10order by customer_id, created_at;
order_idcustomer_idcreated_atorder_number
1001c_anna2026-01-04 09:121
1003c_anna2026-02-02 11:052
1006c_anna2026-03-21 18:003
1002c_ben2026-01-09 14:301
1005c_ben2026-03-03 10:202
1004c_cara2026-02-14 16:451
1008c_cara2026-04-08 08:552
1007c_dev2026-03-25 12:101
1009c_dev2026-04-19 19:402

order_number = 1 is the first order, order_number > 1 is a repeat purchase. Order by created_at desc instead and 1 is the latest order.

QUALIFY in SQL: keep only the first row

You cannot write where row_number() over (...) = 1, because WHERE runs before window functions exist. QUALIFY is a filter that runs after them, the way HAVING runs after GROUP BY:

SQL
1select order_id, customer_id, created_at, total_price
2from orders
3qualify row_number() over (
4    partition by customer_id
5    order by created_at
6) = 1
7order by created_at;
order_idcustomer_idcreated_attotal_price
1001c_anna2026-01-04 09:12120.00
1002c_ben2026-01-09 14:3080.00
1004c_cara2026-02-14 16:45200.00
1007c_dev2026-03-25 12:10150.00

The same pattern is the standard way to deduplicate synced data: when a source sends the same record more than once, qualify row_number() over (partition by id order by updated_at desc) = 1 keeps the newest version of each.

QUALIFY works in BigQuery, Snowflake, Databricks, Redshift and DuckDB. Redshift wants a table alias when QUALIFY follows FROM directly, so write from orders o qualify ... there. PostgreSQL does not have it and returns a syntax error. Wrap the window in a subquery or CTE and filter outside:

SQL
1-- PostgreSQL
2select order_id, customer_id, created_at, total_price
3from (
4    select
5        *,
6        row_number() over (
7            partition by customer_id
8            order by created_at
9        ) as order_number
10    from orders
11) as ranked
12where order_number = 1
13order by created_at;

PostgreSQL also has select distinct on (customer_id) ... order by customer_id, created_at, which returns the same four rows here.

Break ties on purpose. If two orders share a timestamp, ROW_NUMBER picks one of them arbitrarily, and the pick can change between runs. Add a tiebreaker such as order by created_at, order_id so the result is the same every time.

ROW_NUMBER vs RANK vs DENSE_RANK

The three ranking functions only differ when there are ties. Ranking customers by revenue, where c_anna and c_dev both spent 220:

SQL
1select
2    customer_id,
3    sum(total_price) as revenue,
4    row_number() over (
5        order by sum(total_price) desc
6    ) as row_num,
7    rank() over (order by sum(total_price) desc) as rnk,
8    dense_rank() over (
9        order by sum(total_price) desc
10    ) as dense_rnk
11from orders
12group by customer_id
13order by revenue desc;
customer_idrevenuerow_numrnkdense_rnk
c_cara310.00111
c_anna220.00222
c_dev220.00322
c_ben175.00443
  • ROW_NUMBER always gives unique numbers. Use it to pick exactly one row.
  • RANK gives ties the same number and then skips, like a sports table. Use it for "top 3 customers", where a tie for third should include both.
  • DENSE_RANK gives ties the same number without gaps. Use it for "the second highest value".

2. Month over month growth: LAG and LEAD

LAG(x) returns x from the previous row in the window's order, and LEAD(x) from the next one. With this month and last month on the same row, a growth rate is one line of arithmetic. Take monthly revenue, the kind of table a Shopify sales report produces:

monthrevenue
2026-01-0140000
2026-02-0146000
2026-03-0143700
2026-04-0152440
SQL
1with monthly as (
2    select
3        month,
4        revenue,
5        lag(revenue) over (order by month) as prev_revenue
6    from monthly_revenue
7)
8select
9    month,
10    revenue,
11    prev_revenue,
12    round(
13        100.0 * (revenue - prev_revenue)
14            / nullif(prev_revenue, 0),
15        1
16    ) as mom_growth_pct
17from monthly
18order by month;

The CTE computes LAG once and names it, so the growth formula reads like the one in a spreadsheet.

monthrevenueprev_revenuemom_growth_pct
2026-01-0140000nullnull
2026-02-01460004000015.0
2026-03-014370046000-5.0
2026-04-01524404370020.0

Three details to get right before this goes on a dashboard:

  • The first month is null, because there is no previous row. That is usually what you want on a chart. lag(revenue, 1, 0) returns a default instead, but a growth rate against 0 means nothing, which is also why the division goes through nullif(..., 0).
  • Year over year is lag(revenue, 12), as long as every month has a row. LAG counts rows, not months: if a month with no sales is missing from the table, the comparison silently shifts. Build months from a calendar table or a date spine first.
  • For growth per product or per market, add partition by product_id so one product's previous month is never another product's.

LEAD: days until the next order

LEAD looks forward. Partitioned by customer, it gives the gap between each order and the next one, which is the raw material for repurchase rates and "how long until they come back":

SQL
1select
2    order_id,
3    customer_id,
4    cast(created_at as date) as order_date,
5    datediff(
6        'day',
7        created_at,
8        lead(created_at) over (
9            partition by customer_id
10            order by created_at
11        )
12    ) as days_to_next_order
13from orders
14order by customer_id, created_at;
order_idcustomer_idorder_datedays_to_next_order
1001c_anna2026-01-0429
1003c_anna2026-02-0247
1006c_anna2026-03-21null
1002c_ben2026-01-0953
1005c_ben2026-03-03null
1004c_cara2026-02-1453
1008c_cara2026-04-08null
1007c_dev2026-03-2525
1009c_dev2026-04-19null

The null rows are each customer's latest order: no next order yet. datediff('day', a, b) is the DuckDB spelling. Snowflake writes datediff(day, a, b), BigQuery date_diff(b, a, day), and PostgreSQL subtracts two dates directly.

3. Running MRR: a running total over Stripe movements

MRR at the end of a month is the sum of every MRR change up to that month: new subscriptions, expansions, contractions and churn. That is a running total. Here is a table of MRR movements of the kind you derive from Stripe subscriptions (the MRR with Stripe and SQL guide shows how to get there):

monthcustomer_idplanmovementmrr_change
2026-01-01cus_Apronew100
2026-01-01cus_Bbasicnew50
2026-02-01cus_Cpronew200
2026-03-01cus_Bbasicexpansion50
2026-03-01cus_Aprochurn-100
2026-04-01cus_Dbasicnew150
SQL
1select
2    month,
3    sum(mrr_change) as net_new_mrr,
4    sum(sum(mrr_change)) over (
5        order by month
6        rows between unbounded preceding and current row
7    ) as mrr
8from mrr_movements
9group by month
10order by month;
monthnet_new_mrrmrr
2026-01-01150150
2026-02-01200350
2026-03-01-50300
2026-04-01150450

The sum(sum(...)) is not a typo. The inner SUM is the GROUP BY aggregate, net new MRR per month. The outer SUM ... OVER runs afterwards on those grouped rows and adds them up in month order. For what counts as MRR in the first place (annual plans, discounts, trials), see how to calculate MRR.

MRR per plan

To split MRR by plan, add plan in three places: the select list, the GROUP BY, and a PARTITION BY so each plan gets its own running total:

SQL
1select
2    month,
3    plan,
4    sum(mrr_change) as net_new_mrr,
5    sum(sum(mrr_change)) over (
6        partition by plan
7        order by month
8        rows between unbounded preceding and current row
9    ) as mrr
10from mrr_movements
11group by month, plan
12order by plan, month;
monthplannet_new_mrrmrr
2026-01-01basic5050
2026-03-01basic50100
2026-04-01basic150250
2026-01-01pro100100
2026-02-01pro200300
2026-03-01pro-100200

Basic has no February row and pro has no April row, because nothing changed on those plans in those months. The running total is still right, but a chart would skip the month. If every plan needs a row for every month, cross join the plans with a calendar of months first and fill the gaps with 0.

Share of total: a window over everything

An empty OVER () makes the whole result one window. Around an aggregate, that gives each row's share of the grand total, here each customer's share of Shopify revenue:

SQL
1select
2    customer_id,
3    sum(total_price) as revenue,
4    round(
5        100.0 * sum(total_price) / sum(sum(total_price)) over (),
6        1
7    ) as share_pct
8from orders
9group by customer_id
10order by revenue desc, customer_id;
customer_idrevenueshare_pct
c_cara310.0033.5
c_anna220.0023.8
c_dev220.0023.8
c_ben175.0018.9

Swap over () for over (partition by country) and each customer's share is of their own country's revenue. Divide sum(sum(total_price)) over (order by sum(total_price) desc, customer_id rows between unbounded preceding and current row) by the same grand total and you get a running share instead: 33.5, 57.3, 81.1 and 100 here, the curve behind a Pareto or "top 20% of customers" chart.

4. Running totals and moving averages in SQL: the frame clause

The frame is the third part of OVER (...). It picks which rows of the partition feed the current row's result, measured from the current row:

  • rows between unbounded preceding and current row: from the start of the partition to here. A running total.
  • rows between 6 preceding and current row: the current row and the six before it. A 7 row moving average.
  • rows between 1 preceding and 1 following: a centred 3 row window.
Window frames on ten days of revenue, with Mar 8 as the current row. A running total uses ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, so the frame runs from Mar 1 to Mar 8 and sums to 4,010. A 7-day moving average uses ROWS BETWEEN 6 PRECEDING AND CURRENT ROW, so the frame is Mar 2 to Mar 8 and averages 512.9. If Mar 5 has no row, ROWS still takes seven rows and reaches back to Mar 1, eight calendar days, averaging 530.0, while RANGE BETWEEN INTERVAL 6 DAYS PRECEDING takes only the six rows dated Mar 2 to Mar 8 and averages 548.3.

A 7 day moving average of daily revenue

Daily revenue is noisy: one big order on Mar 6 makes the line jump. A trailing 7 day average smooths it out:

SQL
1select
2    day,
3    revenue,
4    round(avg(revenue) over (
5        order by day
6        rows between 6 preceding and current row
7    ), 1) as revenue_7d_avg
8from daily_revenue
9order by day;
dayrevenuerevenue_7d_avg
2026-03-01420420.0
2026-03-02380400.0
2026-03-03510436.7
2026-03-04460442.5
2026-03-05300414.0
2026-03-06940501.7
2026-03-07610517.1
2026-03-08390512.9
2026-03-09450522.9
2026-03-10520524.3

The first six days average fewer than seven values, because the frame cannot reach back further than the partition. Either label them as a warm up, or hide them with case when count(*) over (order by day rows between 6 preceding and current row) = 7 then ... end.

ROWS vs RANGE: when days are missing

ROWS counts rows. If a day with no sales has no row, rows between 6 preceding reaches back eight calendar days instead of seven. RANGE counts values of the ORDER BY column instead, so range between interval '6 days' preceding and current row always covers seven calendar days. Remove Mar 5 from the table and the two give different answers on Mar 8:

dayrevenue7 rows (ROWS)7 days (RANGE)
2026-03-06940542.0542.0
2026-03-07610553.3553.3
2026-03-08390530.0548.3
2026-03-09450534.3560.0
2026-03-10520554.3561.7

Which is right depends on the question. If a day without sales should count as a zero, neither is: join to a calendar table so the missing day becomes a row with 0, then use ROWS. If you only want to average days that had activity, RANGE with an interval is the honest one. Snowflake and PostgreSQL accept range between interval '6 days' preceding and current row. BigQuery only allows numeric RANGE offsets, so order by unix_date(day) and write range between 6 preceding and current row.

The default frame and ties

If you write order by without a frame, the default is range between unbounded preceding and current row in BigQuery, Snowflake and PostgreSQL for aggregates like SUM. With RANGE, rows that share the same ORDER BY value are peers and are added together. Two Stripe payments on the same day show the difference:

paid_onamountsum(amount) over (order by paid_on)with rows between unbounded preceding and current row
2026-03-01100100100
2026-03-0240200140
2026-03-0260200200
2026-03-0380280280

If you expected a row by row running total, the default gives you 200 twice. Write the frame out whenever the result depends on it. Snowflake's documentation recommends exactly that, and it has one more reason: for FIRST_VALUE, LAST_VALUE and NTH_VALUE, Snowflake's default frame is the whole partition, while BigQuery and PostgreSQL stop at the current row. last_value(x) over (order by day) therefore returns the last value of the partition in Snowflake, and in the other two the current row's own value (or that of the last row tied with it).

5. Cohort retention in one query

Cohort retention answers "of the customers who first bought in January, how many bought again one, two, three months later?". It usually gets built in several models, but window functions do it in one query: one window to find each customer's first month, and one window over the grouped result to find each cohort's size.

SQL
1with customer_months as (
2    select distinct
3        customer_id,
4        date_trunc('month', created_at) as order_month,
5        min(date_trunc('month', created_at)) over (
6            partition by customer_id
7        ) as cohort_month
8    from orders
9)
10select
11    cohort_month,
12    datediff('month', cohort_month, order_month) as month_number,
13    count(*) as active_customers,
14    round(100.0 * count(*) / first_value(count(*)) over (
15        partition by cohort_month
16        order by order_month
17    ), 0) as retention_pct
18from customer_months
19group by cohort_month, order_month
20order by cohort_month, month_number;
cohort_monthmonth_numberactive_customersretention_pct
2026-01-0102100
2026-01-011150
2026-01-0122100
2026-02-0101100
2026-02-0121100
2026-03-0101100
2026-03-0111100

Step by step:

  1. min(...) over (partition by customer_id) stamps every order month with the customer's first month, their cohort. distinct keeps one row per customer per active month, so a customer who orders three times in a month counts once.
  2. group by cohort_month, order_month counts active customers per cohort per month.
  3. first_value(count(*)) over (partition by cohort_month order by order_month) reads the month 0 count, the cohort size, onto every row of that cohort. Dividing by it gives retention.

Read it as: of the two customers who started in January (c_anna and c_ben), one came back in February (50%) and both ordered in March (100%). Retention is not always falling, because a customer who skips a month counts again when they return. A month with no returning customers has no row at all, as with February's cohort in month 1.

Pivot month_number into columns in your BI tool and you get the classic retention triangle. The missing rows become 0%, and the blank cells are months that have not happened yet, because the orders stop in April:

cohortcustomersmonth 0month 1month 2month 3
Jan 20262100%50%100%0%
Feb 20261100%0%100%
Mar 20261100%100%

Read down a column to compare cohorts at the same age, and along a row to follow one cohort over time.

The same query works for subscriptions: swap orders for invoices or active subscription months from Stripe, and it becomes logo retention. Sum MRR instead of counting customers and you get revenue retention.

BigQuery, Snowflake and PostgreSQL differences

The window functions themselves (ROW_NUMBER, RANK, LAG, SUM ... OVER and the rest) are standard SQL and work the same in all three. The differences are in the clauses and date functions around them:

BigQuerySnowflakePostgreSQL
QUALIFYYesYesNo. Filter in a subquery or CTE, or use DISTINCT ON
Truncate to monthdate_trunc(created_at, month)date_trunc('month', created_at)date_trunc('month', created_at)
Months between two datesdate_diff(order_month, cohort_month, month)datediff(month, cohort_month, order_month)(extract(year from b) - extract(year from a)) * 12 + extract(month from b) - extract(month from a)
Days between two datesdate_diff(b, a, day)datediff(day, a, b)b::date - a::date
ORDER BY inside OVERRequired for LAG and LEADRequired for ROW_NUMBER, LAG and LEADOptional, but the order is arbitrary without it
RANGE with a date offsetNo, numeric only: order by unix_date(day) range between 6 preceding and current rowYes: range between interval '6 days' preceding and current rowYes: range between interval '6 days' preceding and current row
Default frame for FIRST_VALUE / LAST_VALUE with ORDER BYStart of partition to current rowWhole partitionStart of partition to current row

Redshift is stricter than all three. It has QUALIFY, but its frames are ROWS only, and an aggregate or FIRST_VALUE / LAST_VALUE window with ORDER BY needs an explicit frame or the query fails. Add rows between unbounded preceding and current row to the running totals and the cohort query before running them there.

DuckDB, which runs the examples in this post, accepts QUALIFY, date_trunc('month', x) and datediff('month', a, b) with the date part in quotes. Checked against the BigQuery, Snowflake and PostgreSQL documentation between 29 October and 4 November 2026.

Common mistakes

  • Filtering on a window function in WHERE. It fails, because WHERE runs first. Use QUALIFY, or a subquery in PostgreSQL.
  • Leaving out the tiebreaker. ROW_NUMBER over a non-unique ORDER BY gives a different "first" row from run to run.
  • Trusting the default frame. Running totals with ties and LAST_VALUE both behave unexpectedly without an explicit ROWS BETWEEN.
  • LAG over gaps. LAG and ROWS count rows, not time. Fill missing days and months from a calendar table before comparing periods.
  • Forgetting PARTITION BY. Without it, the previous row for one product is the last row of another.
  • Mixing DISTINCT and windows. DISTINCT runs after window functions, so select distinct customer_id, count(*) over () counts rows before deduplication.

Turning these queries into metrics you keep

A query you run once answers a question. The same query saved as a model that refreshes after every sync becomes a metric the whole company uses. In Weld, the SQL editor runs directly against your warehouse, so everything above works as written in your own dialect, and models can be scheduled to run after your Stripe or Shopify data lands. If you would rather not start from a blank editor, the ready made Stripe MRR models build MRR per customer per month and split it into new, expansion, contraction and churn, the movements used in section 3, and the Shopify sales models rebuild daily sales, the input for the moving average.

New to SQL? The free Learn SQL course covers the basics this guide builds on, from GROUP BY to CTEs.

FAQ

Additional resources