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_NUMBERfor "first" and "latest",LAGfor growth rates,SUMwith a frame for running totals,AVGwith a frame for moving averages, andFIRST_VALUEfor cohort retention.
Which window function answers which question
| The question | Window function | Where |
|---|---|---|
| What did each customer buy first? Which record is the latest? | ROW_NUMBER() with QUALIFY | Section 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_id | customer_id | created_at | total_price |
|---|---|---|---|
| 1001 | c_anna | 2026-01-04 09:12 | 120.00 |
| 1002 | c_ben | 2026-01-09 14:30 | 80.00 |
| 1003 | c_anna | 2026-02-02 11:05 | 60.00 |
| 1004 | c_cara | 2026-02-14 16:45 | 200.00 |
| 1005 | c_ben | 2026-03-03 10:20 | 95.00 |
| 1006 | c_anna | 2026-03-21 18:00 | 40.00 |
| 1007 | c_dev | 2026-03-25 12:10 | 150.00 |
| 1008 | c_cara | 2026-04-08 08:55 | 110.00 |
| 1009 | c_dev | 2026-04-19 19:40 | 70.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.
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_id | customer_id | total_price | customer_revenue | running_revenue |
|---|---|---|---|---|
| 1001 | c_anna | 120.00 | 220.00 | 120.00 |
| 1003 | c_anna | 60.00 | 220.00 | 180.00 |
| 1006 | c_anna | 40.00 | 220.00 | 220.00 |
| 1002 | c_ben | 80.00 | 175.00 | 80.00 |
| 1005 | c_ben | 95.00 | 175.00 | 175.00 |
| 1004 | c_cara | 200.00 | 310.00 | 200.00 |
| 1008 | c_cara | 110.00 | 310.00 | 310.00 |
| 1007 | c_dev | 150.00 | 220.00 | 150.00 |
| 1009 | c_dev | 70.00 | 220.00 | 220.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 forROW_NUMBER,LAGandLEAD. Snowflake rejects those three without it and BigQuery rejectsLAGandLEAD; 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:
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_id | customer_id | created_at | order_number |
|---|---|---|---|
| 1001 | c_anna | 2026-01-04 09:12 | 1 |
| 1003 | c_anna | 2026-02-02 11:05 | 2 |
| 1006 | c_anna | 2026-03-21 18:00 | 3 |
| 1002 | c_ben | 2026-01-09 14:30 | 1 |
| 1005 | c_ben | 2026-03-03 10:20 | 2 |
| 1004 | c_cara | 2026-02-14 16:45 | 1 |
| 1008 | c_cara | 2026-04-08 08:55 | 2 |
| 1007 | c_dev | 2026-03-25 12:10 | 1 |
| 1009 | c_dev | 2026-04-19 19:40 | 2 |
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:
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_id | customer_id | created_at | total_price |
|---|---|---|---|
| 1001 | c_anna | 2026-01-04 09:12 | 120.00 |
| 1002 | c_ben | 2026-01-09 14:30 | 80.00 |
| 1004 | c_cara | 2026-02-14 16:45 | 200.00 |
| 1007 | c_dev | 2026-03-25 12:10 | 150.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:
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_NUMBERpicks one of them arbitrarily, and the pick can change between runs. Add a tiebreaker such asorder by created_at, order_idso 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:
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_id | revenue | row_num | rnk | dense_rnk |
|---|---|---|---|---|
| c_cara | 310.00 | 1 | 1 | 1 |
| c_anna | 220.00 | 2 | 2 | 2 |
| c_dev | 220.00 | 3 | 2 | 2 |
| c_ben | 175.00 | 4 | 4 | 3 |
ROW_NUMBERalways gives unique numbers. Use it to pick exactly one row.RANKgives 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_RANKgives 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:
| month | revenue |
|---|---|
| 2026-01-01 | 40000 |
| 2026-02-01 | 46000 |
| 2026-03-01 | 43700 |
| 2026-04-01 | 52440 |
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.
| month | revenue | prev_revenue | mom_growth_pct |
|---|---|---|---|
| 2026-01-01 | 40000 | null | null |
| 2026-02-01 | 46000 | 40000 | 15.0 |
| 2026-03-01 | 43700 | 46000 | -5.0 |
| 2026-04-01 | 52440 | 43700 | 20.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 throughnullif(..., 0). - Year over year is
lag(revenue, 12), as long as every month has a row.LAGcounts 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_idso 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":
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_id | customer_id | order_date | days_to_next_order |
|---|---|---|---|
| 1001 | c_anna | 2026-01-04 | 29 |
| 1003 | c_anna | 2026-02-02 | 47 |
| 1006 | c_anna | 2026-03-21 | null |
| 1002 | c_ben | 2026-01-09 | 53 |
| 1005 | c_ben | 2026-03-03 | null |
| 1004 | c_cara | 2026-02-14 | 53 |
| 1008 | c_cara | 2026-04-08 | null |
| 1007 | c_dev | 2026-03-25 | 25 |
| 1009 | c_dev | 2026-04-19 | null |
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):
| month | customer_id | plan | movement | mrr_change |
|---|---|---|---|---|
| 2026-01-01 | cus_A | pro | new | 100 |
| 2026-01-01 | cus_B | basic | new | 50 |
| 2026-02-01 | cus_C | pro | new | 200 |
| 2026-03-01 | cus_B | basic | expansion | 50 |
| 2026-03-01 | cus_A | pro | churn | -100 |
| 2026-04-01 | cus_D | basic | new | 150 |
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;| month | net_new_mrr | mrr |
|---|---|---|
| 2026-01-01 | 150 | 150 |
| 2026-02-01 | 200 | 350 |
| 2026-03-01 | -50 | 300 |
| 2026-04-01 | 150 | 450 |
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:
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;| month | plan | net_new_mrr | mrr |
|---|---|---|---|
| 2026-01-01 | basic | 50 | 50 |
| 2026-03-01 | basic | 50 | 100 |
| 2026-04-01 | basic | 150 | 250 |
| 2026-01-01 | pro | 100 | 100 |
| 2026-02-01 | pro | 200 | 300 |
| 2026-03-01 | pro | -100 | 200 |
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:
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_id | revenue | share_pct |
|---|---|---|
| c_cara | 310.00 | 33.5 |
| c_anna | 220.00 | 23.8 |
| c_dev | 220.00 | 23.8 |
| c_ben | 175.00 | 18.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.
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:
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;| day | revenue | revenue_7d_avg |
|---|---|---|
| 2026-03-01 | 420 | 420.0 |
| 2026-03-02 | 380 | 400.0 |
| 2026-03-03 | 510 | 436.7 |
| 2026-03-04 | 460 | 442.5 |
| 2026-03-05 | 300 | 414.0 |
| 2026-03-06 | 940 | 501.7 |
| 2026-03-07 | 610 | 517.1 |
| 2026-03-08 | 390 | 512.9 |
| 2026-03-09 | 450 | 522.9 |
| 2026-03-10 | 520 | 524.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:
| day | revenue | 7 rows (ROWS) | 7 days (RANGE) |
|---|---|---|---|
| 2026-03-06 | 940 | 542.0 | 542.0 |
| 2026-03-07 | 610 | 553.3 | 553.3 |
| 2026-03-08 | 390 | 530.0 | 548.3 |
| 2026-03-09 | 450 | 534.3 | 560.0 |
| 2026-03-10 | 520 | 554.3 | 561.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_on | amount | sum(amount) over (order by paid_on) | with rows between unbounded preceding and current row |
|---|---|---|---|
| 2026-03-01 | 100 | 100 | 100 |
| 2026-03-02 | 40 | 200 | 140 |
| 2026-03-02 | 60 | 200 | 200 |
| 2026-03-03 | 80 | 280 | 280 |
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.
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_month | month_number | active_customers | retention_pct |
|---|---|---|---|
| 2026-01-01 | 0 | 2 | 100 |
| 2026-01-01 | 1 | 1 | 50 |
| 2026-01-01 | 2 | 2 | 100 |
| 2026-02-01 | 0 | 1 | 100 |
| 2026-02-01 | 2 | 1 | 100 |
| 2026-03-01 | 0 | 1 | 100 |
| 2026-03-01 | 1 | 1 | 100 |
Step by step:
min(...) over (partition by customer_id)stamps every order month with the customer's first month, their cohort.distinctkeeps one row per customer per active month, so a customer who orders three times in a month counts once.group by cohort_month, order_monthcounts active customers per cohort per month.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:
| cohort | customers | month 0 | month 1 | month 2 | month 3 |
|---|---|---|---|---|---|
| Jan 2026 | 2 | 100% | 50% | 100% | 0% |
| Feb 2026 | 1 | 100% | 0% | 100% | |
| Mar 2026 | 1 | 100% | 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:
| BigQuery | Snowflake | PostgreSQL | |
|---|---|---|---|
QUALIFY | Yes | Yes | No. Filter in a subquery or CTE, or use DISTINCT ON |
| Truncate to month | date_trunc(created_at, month) | date_trunc('month', created_at) | date_trunc('month', created_at) |
| Months between two dates | date_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 dates | date_diff(b, a, day) | datediff(day, a, b) | b::date - a::date |
ORDER BY inside OVER | Required for LAG and LEAD | Required for ROW_NUMBER, LAG and LEAD | Optional, but the order is arbitrary without it |
RANGE with a date offset | No, numeric only: order by unix_date(day) range between 6 preceding and current row | Yes: range between interval '6 days' preceding and current row | Yes: range between interval '6 days' preceding and current row |
Default frame for FIRST_VALUE / LAST_VALUE with ORDER BY | Start of partition to current row | Whole partition | Start 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, becauseWHEREruns first. UseQUALIFY, or a subquery in PostgreSQL. - Leaving out the tiebreaker.
ROW_NUMBERover a non-uniqueORDER BYgives a different "first" row from run to run. - Trusting the default frame. Running totals with ties and
LAST_VALUEboth behave unexpectedly without an explicitROWS BETWEEN. LAGover gaps.LAGandROWScount 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
DISTINCTand windows.DISTINCTruns after window functions, soselect 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
A window function calculates a value for each row using a set of related rows, called the window, without collapsing them into one row. You recognise one by its OVER clause, for example sum(revenue) over (partition by customer_id order by created_at).
GROUP BY returns one row per group. A window function returns every input row and adds a value computed across its group. Use GROUP BY for totals per customer, and a window function when you need each order next to its customer's total, rank or running total.
QUALIFY filters rows on the result of a window function, the way HAVING filters on an aggregate. The common use is keeping one row per group, as in qualify row_number() over (partition by customer_id order by created_at) = 1. It is supported in BigQuery, Snowflake, Databricks, Redshift and DuckDB, but not in PostgreSQL.
Use sum(amount) over (order by date rows between unbounded preceding and current row). Add partition by to restart the total per customer or product. Write the rows between frame out, because the default frame adds up rows with the same date together.
Divide each row's value by a window sum over everything: 100.0 * revenue / sum(revenue) over (). If the query already groups, wrap the aggregate: sum(total_price) / sum(sum(total_price)) over (). Add partition by inside the OVER to get the share within a group, such as a country, instead of the grand total.
They differ only on ties. ROW_NUMBER always gives unique numbers (1, 2, 3, 4), RANK gives tied rows the same number and skips the next ones (1, 2, 2, 4), and DENSE_RANK gives tied rows the same number without gaps (1, 2, 2, 3).
Yes. PostgreSQL supports all the standard window functions and frames, including RANGE with interval offsets. The one clause it lacks is QUALIFY, so filter window results in a subquery or CTE instead.



