Up to now, most aggregate queries we write return one row per group. That works for totals, but it fails when we need the detail and the total side by side. Take a report such as "each order and its share of the customer total" on a table with millions of orders. It would need a join back to a grouped copy of the same table. Window functions solve this in one pass, so the detail rows stay and a new column carries the calculation.
GROUP BY collapses rows, a window function keeps them
With GROUP BY, ten orders from one customer become one row. With a window function, we keep all ten rows and add a column that is calculated across them. To split the rows into groups, we use PARTITION BY. To set the order that ranking and running calculations follow, we use ORDER BY inside OVER.
SELECT order_id, customer_id, total_amount,
total_amount * 1.0 / SUM(total_amount) OVER (PARTITION BY customer_id) AS share_of_customer
FROM orders;Each row now shows its own amount and its share of that customer's total, so the result still has one row per order.
ROW_NUMBER, RANK and DENSE_RANK
To number rows in a group, we use one of three functions. They behave the same until two values tie. Take the scores 100, 100 and 90.
| Score | ROW_NUMBER | RANK | DENSE_RANK |
|---|---|---|---|
| 100 | 1 | 1 | 1 |
| 100 | 2 | 1 | 1 |
| 90 | 3 | 3 | 2 |
ROW_NUMBERnever repeats a number, so tied rows get an arbitrary order.RANKgives tied rows the same number and then skips (1, 1, 3).DENSE_RANKgives tied rows the same number without skipping (1, 1, 2).
In a school league table, two students tie for first place. RANK says the next student is third, as in a race. DENSE_RANK says second. ROW_NUMBER simply lists the students in some order.
Top N per group
This is a top-N-per-group problem. Since windows are calculated after WHERE runs, we cannot filter on a window function in the same SELECT. As a result, we put the window in a CTE and filter in the outer query.
WITH ranked AS (
SELECT product, category, revenue,
ROW_NUMBER() OVER (PARTITION BY category ORDER BY revenue DESC) AS rn
FROM product_revenue
)
SELECT * FROM ranked WHERE rn <= 3;Some databases, such as Snowflake, BigQuery and DuckDB, offer QUALIFY to filter on a window directly. PostgreSQL does not, so the CTE is the portable choice.
LAG and LEAD: compare with the previous or next row
To compare a month with the one before it, we use LAG. LEAD does the same with the next row.
SELECT month, revenue,
revenue - LAG(revenue) OVER (ORDER BY month) AS change_vs_prev
FROM monthly_revenue;The first month has no previous row, so LAG returns NULL there. If 0 is a fair starting point, a third argument sets a default, for example LAG(revenue, 1, 0). The default saves a step, but it can also hide the fact that the first month has no baseline, so choose it on purpose.
Running totals and the frame trap
A running total adds each row to everything before it. In the query below, the first column leaves the frame out and the second states it.
SELECT order_date, revenue,
SUM(revenue) OVER (ORDER BY order_date) AS running_default,
SUM(revenue) OVER (ORDER BY order_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_rows
FROM daily_revenue;The same default frame explains why LAST_VALUE often returns the current row instead of the last row of the group. Extending the frame to UNBOUNDED FOLLOWING gives the real last value.
A check you can run every time
- Count the rows before and after. A window function must not change the row count.
- Pick one partition and calculate five rows by hand.
- If the result involves ties, run it once with
RANKand once withROW_NUMBER, then compare.


