SQL window functions by example
Five window function patterns with one small orders table: ranking, running totals, previous row, share of total and moving average.
A window function calculates a value for each row using a group of related rows, without collapsing the rows the way group by does. They look odd at first because of the over (...) part. A small example makes them clear.
The table
-- orders(order_id, customer, order_date, amount)
-- 1 Ana 2026-01-03 40
-- 2 Ana 2026-01-20 25
-- 3 Ben 2026-01-05 60
-- 4 Ana 2026-02-02 35
-- 5 Ben 2026-02-11 20
1. Rank within a group
"Number each customer's orders from oldest to newest."
select customer, order_date, amount,
row_number() over (partition by customer order by order_date) as n
from orders;
partition by makes one window per customer. order by sets the order inside the window. Use rank() or dense_rank() when ties should share a number.
2. Running total
select customer, order_date, amount,
sum(amount) over (partition by customer order by order_date) as running_total
from orders;
With an order by, the default frame runs from the first row to the current one, so each row shows the total so far.
3. The previous row
"How many days since this customer's last order?"
select customer, order_date,
order_date - lag(order_date) over (partition by customer order by order_date) as days_since_last
from orders;
lag looks back one row. lead looks forward. The first row in each window gets null.
4. Share of the total
select customer, amount,
amount * 1.0 / sum(amount) over () as share_of_all
from orders;
An empty over () means the window is the whole table, so you can mix a row value with a total in one select.
5. Moving average
select order_date, amount,
avg(amount) over (order by order_date rows between 2 preceding and current row) as avg_last_3
from orders;
The rows between clause sets the frame exactly: this row and the two before it.
Mistakes to avoid
- Filtering on a window result. You cannot put
where n = 1onrow_number()in the same select. Wrap it in a subquery or a CTE, then filter. - Forgetting the order. Without
order by,row_number()is arbitrary. - Mixing up
group byandpartition by. Group by reduces rows. Partition by keeps them.
If you can explain these five out loud on a small table, you can handle most window questions in an analyst interview.