Databases · Intermediate · 24 min
Answer ranking and running-total questions with SQL window functions
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · PostgreSQL 18.7
You will use PostgreSQL 18 window functions to rank products per region with ties handled on purpose, keep running totals and 7-day averages, compare each month with the one before, and save the answers in a report file you can run again.
On this page
GROUP BY squashes rows into one row per group. That answers "how much did each region sell?" but not "which three products sold best in each region?", "what was the total so far on each day?" or "how did this month compare with last month?". Those questions need each row to see other rows while staying a row of its own. That is what a window function does.
In this tutorial you load four months of orders from a small online shop into PostgreSQL 18 and answer those questions one function at a time: row_number, rank and dense_rank for rankings, sum() OVER for running totals and shares, avg() with a frame for moving averages, lag for month-on-month change, first_value and last_value per customer, and ntile for quartiles. The data is generated by a fixed pattern, so your output matches the tables below row for row. Amounts are whole units of any currency: read them as naira, cedis or shillings.
You need PostgreSQL 18 on Ubuntu 26.04, installed as in /tutorials/install-postgresql-18-on-ubuntu-26-04. PostgreSQL 19.0 came out on 19 November 2026; this tutorial stays on 18, like the other database tutorials here. If GROUP BY and HAVING are new to you, do /tutorials/summarise-data-with-group-by-and-having first.
Step 1 · Load four months of orders
Make a throwaway folder and a database called shop:
mkdir -p ~/sql-window-demo
sudo -u postgres createdb shopWrite the data file. It creates one table, orders, and fills it from generate_series(1, 240): two orders a day from 1 January to 30 April 2026, with each order's region, customer, product and quantity worked out from its number. The shop does not trade on Sundays, so the WHERE drops those days. The gaps matter in the moving-average step.
cat > ~/sql-window-demo/orders.sql <<'SQL'
\set ON_ERROR_STOP on
DROP TABLE IF EXISTS orders;
CREATE TABLE orders (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
ordered_on date NOT NULL,
region text NOT NULL,
customer text NOT NULL,
product text NOT NULL,
quantity integer NOT NULL,
amount numeric(10,2) NOT NULL
);
INSERT INTO orders (ordered_on, region, customer, product, quantity, amount)
SELECT
date '2026-01-01' + (g - 1) / 2,
(ARRAY['North', 'South', 'East', 'West'])[1 + g % 4],
'cust-' || lpad((1 + g * 7 % 10)::text, 2, '0'),
(ARRAY['Rice 5 kg', 'Garri 2 kg', 'Palm oil 5 L', 'Solar lamp',
'Phone charger', 'Bar soap'])[1 + (g / 7 + g) % 6],
1 + g % 3,
(ARRAY[3000, 1500, 4500, 6000, 2000, 1000])[1 + (g / 7 + g) % 6] * (1 + g % 3)
FROM generate_series(1, 240) AS g
WHERE extract(isodow FROM date '2026-01-01' + (g - 1) / 2) <> 7
ORDER BY g;
SQLLoad it. The < redirect is read by your own shell, so the postgres user does not need access to your home folder:
sudo -u postgres psql -d shop < ~/sql-window-demo/orders.sqlpsql prints a notice that the table did not exist (the first time only), then DROP TABLE, CREATE TABLE and INSERT 0 206.
Check it worked
sudo -u postgres psql -d shop -c "SELECT count(*) AS orders, count(DISTINCT ordered_on) AS trading_days, sum(amount) AS revenue FROM orders;"You see 206 orders over 103 trading days and revenue of 1214500.00. Order 1 is two bags of Garri 2 kg for cust-08 in the South region on 1 January, worth 3000.00.
Step 2 · Rank products within each region
Open an interactive session for the rest of the queries:
sudo -u postgres psql -d shopThe prompt is shop=#. A statement can span several lines and ends at the ;.
A window function is an ordinary function followed by OVER (...). Inside the brackets, PARTITION BY splits the rows into groups that are numbered separately, and ORDER BY sets the order within each group. Unlike GROUP BY, nothing is collapsed: every input row keeps its own output row.
Rank each product by revenue inside its region, using all three ranking functions side by side. Two regions are enough to see the differences:
SELECT region,
product,
sum(amount) AS revenue,
row_number() OVER (PARTITION BY region ORDER BY sum(amount) DESC, product) AS row_num,
rank() OVER (PARTITION BY region ORDER BY sum(amount) DESC) AS rnk,
dense_rank() OVER (PARTITION BY region ORDER BY sum(amount) DESC) AS dense_rnk
FROM orders
WHERE region IN ('East', 'North')
GROUP BY region, product
ORDER BY region, row_num; region | product | revenue | row_num | rnk | dense_rnk
--------+---------------+-----------+---------+-----+-----------
East | Palm oil 5 L | 108000.00 | 1 | 1 | 1
East | Phone charger | 54000.00 | 2 | 2 | 2
East | Rice 5 kg | 54000.00 | 3 | 2 | 2
East | Solar lamp | 42000.00 | 4 | 4 | 3
East | Garri 2 kg | 18000.00 | 5 | 5 | 4
East | Bar soap | 15000.00 | 6 | 6 | 5
North | Palm oil 5 L | 99000.00 | 1 | 1 | 1
North | Rice 5 kg | 60000.00 | 2 | 2 | 2
North | Phone charger | 54000.00 | 3 | 3 | 3
North | Solar lamp | 54000.00 | 4 | 3 | 3
North | Bar soap | 15000.00 | 5 | 5 | 4
North | Garri 2 kg | 13500.00 | 6 | 6 | 5
(12 rows)Notice sum(amount) inside the OVER clause. The window function runs after GROUP BY, so it ranks the grouped rows, and it can order by an aggregate. Look at the two ties of 54000.00:
row_number()never ties. It gives every row a different number, so for tied rows it has to pick an order. Without the extraproductin itsORDER BY, that pick is arbitrary and can change between runs. Always give it a tie-breaker.rank()gives tied rows the same number and then skips: East goes 1, 2, 2, 4. It answers "how many rows beat this one, plus one".dense_rank()gives tied rows the same number and does not skip: East goes 1, 2, 2, 3.
rank() and dense_rank() treat rows as tied when they are equal on everything in their own ORDER BY. That is why they leave out product: adding it would break every tie.
Check it worked
You get 12 rows. In East, Phone charger and Rice 5 kg both show rnk 2, and the next product is rnk 4 but dense_rnk 3. Check one total by hand: SELECT sum(amount) FROM orders WHERE region = 'East' AND product = 'Rice 5 kg'; returns 54000.00.
Step 3 · Keep the top three per region
The obvious next move is to filter on the rank. Try it:
SELECT region, product, sum(amount) AS revenue
FROM orders
GROUP BY region, product
HAVING rank() OVER (PARTITION BY region ORDER BY sum(amount) DESC) <= 3;ERROR: window functions are not allowed in HAVING
LINE 4: HAVING rank() OVER (PARTITION BY region ORDER BY sum(amount)...
^The error starts with the ERROR: line. psql then echoes line 4 of your query, shortening it with ... if it is long, and puts a caret under rank, the call PostgreSQL rejected.
PostgreSQL works through a query in this order: FROM, then WHERE, then GROUP BY and HAVING, and only then the window functions, followed by DISTINCT, ORDER BY and LIMIT. When WHERE and HAVING run, there is no rank yet to filter on, and the alias rnk does not exist yet either. Window functions are allowed only in the select list and in ORDER BY.
The fix is to compute the rank in one step and filter in the next. A common table expression (WITH ... AS) does that and reads top to bottom:
WITH ranked AS (
SELECT region,
product,
sum(amount) AS revenue,
rank() OVER (PARTITION BY region ORDER BY sum(amount) DESC) AS rnk
FROM orders
GROUP BY region, product
)
SELECT region, product, revenue, rnk
FROM ranked
WHERE rnk <= 3
ORDER BY region, rnk, product; region | product | revenue | rnk
--------+---------------+-----------+-----
East | Palm oil 5 L | 108000.00 | 1
East | Phone charger | 54000.00 | 2
East | Rice 5 kg | 54000.00 | 2
North | Palm oil 5 L | 99000.00 | 1
North | Rice 5 kg | 60000.00 | 2
North | Phone charger | 54000.00 | 3
North | Solar lamp | 54000.00 | 3
South | Solar lamp | 108000.00 | 1
South | Palm oil 5 L | 76500.00 | 2
South | Rice 5 kg | 54000.00 | 3
West | Solar lamp | 108000.00 | 1
West | Palm oil 5 L | 81000.00 | 2
West | Rice 5 kg | 48000.00 | 3
(13 rows)Thirteen rows, not twelve: North has two products tied for third, and rank() keeps both. Which function you choose is a business decision, so ask whoever reads the report:
- "Exactly three per region, ties broken by name":
row_number()with a tie-breaker, 12 rows. - "Top three places, ties share a place":
rank(), 13 rows. - "Top three distinct revenue figures":
dense_rank(), 14 rows, because East's 2, 2, 3 brings inSolar lamptoo.
A subquery in FROM (SELECT ... FROM (SELECT ...) AS ranked WHERE rnk <= 3) works the same way. /tutorials/break-a-long-sql-query-into-steps-with-ctes covers when to prefer each.
Check it worked
The HAVING version fails with window functions are not allowed in HAVING. The CTE version returns 13 rows, with Phone charger and Solar lamp both at rank 3 in North. Swap rank() for dense_rank() in the CTE and the count becomes 14.
Step 4 · Keep a running total
An aggregate with OVER (ORDER BY ...) adds up every row from the start of the partition to the current one. Total each day's sales, then keep a running total of the day totals:
SELECT ordered_on,
sum(amount) AS day_total,
sum(sum(amount)) OVER (ORDER BY ordered_on) AS running_total
FROM orders
GROUP BY ordered_on
ORDER BY ordered_on
LIMIT 6; ordered_on | day_total | running_total
------------+-----------+---------------
2026-01-01 | 16500.00 | 16500.00
2026-01-02 | 10000.00 | 26500.00
2026-01-03 | 6000.00 | 32500.00
2026-01-05 | 4000.00 | 36500.00
2026-01-06 | 10500.00 | 47000.00
2026-01-07 | 15000.00 | 62000.00
(6 rows)sum(sum(amount)) reads oddly but is correct: the inner sum is the GROUP BY aggregate for the day, and the outer sum ... OVER adds those day totals up. Add the first two by hand: 16500 + 10000 = 26500.
Now the trap. Run a running total over individual orders instead of days:
SELECT id,
ordered_on,
amount,
sum(amount) OVER (ORDER BY ordered_on) AS range_total,
sum(amount) OVER (ORDER BY ordered_on, id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS rows_total
FROM orders
ORDER BY id
LIMIT 4; id | ordered_on | amount | range_total | rows_total
----+------------+----------+-------------+------------
1 | 2026-01-01 | 3000.00 | 16500.00 | 3000.00
2 | 2026-01-01 | 13500.00 | 16500.00 | 16500.00
3 | 2026-01-02 | 6000.00 | 26500.00 | 22500.00
4 | 2026-01-02 | 4000.00 | 26500.00 | 26500.00
(4 rows)range_total shows 16500 on order 1, which is already both of the day's orders. The rows a window function adds up are its frame. With ORDER BY and no frame written, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, and RANGE includes the current row's peers: every row with the same ordered_on. rows_total uses ROWS, which counts physical rows, and a unique tie-breaker (id), so it grows one order at a time. When the order column has duplicates, write the frame out.
Add PARTITION BY region before the ORDER BY and the running total starts again from zero for each region.
Check it worked
Your two outputs match the tables above, and order 1 shows range_total 16500.00 but rows_total 3000.00. Drop the LIMIT 6 from the first query and the last row, 30 April, shows a running total of 1214500.00, the same as the revenue you counted in the first step.
Step 5 · Smooth daily sales with a 7-day moving average
A frame does not have to start at the beginning. ROWS BETWEEN 6 PRECEDING AND CURRENT ROW covers the current row and the six before it. RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW covers every row whose date is within six days of the current one. On data with gaps, those are different questions.
Compute both over the daily totals. The WINDOW clause names a window once so the select list stays readable:
WITH daily AS (
SELECT ordered_on AS day, sum(amount) AS day_total
FROM orders
GROUP BY ordered_on
),
averaged AS (
SELECT day,
day_total,
round(avg(day_total) OVER last_7_rows, 2) AS avg_7_rows,
round(avg(day_total) OVER last_7_days, 2) AS avg_7_days,
count(*) OVER last_7_days AS days_in_range
FROM daily
WINDOW last_7_rows AS (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW),
last_7_days AS (ORDER BY day RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW)
)
SELECT *
FROM averaged
WHERE day BETWEEN '2026-01-08' AND '2026-01-14'
ORDER BY day; day | day_total | avg_7_rows | avg_7_days | days_in_range
------------+-----------+------------+------------+---------------
2026-01-08 | 7000.00 | 9857.14 | 8750.00 | 6
2026-01-09 | 9000.00 | 8785.71 | 8583.33 | 6
2026-01-10 | 18000.00 | 9928.57 | 10583.33 | 6
2026-01-12 | 19500.00 | 11857.14 | 13166.67 | 6
2026-01-13 | 7000.00 | 12285.71 | 12583.33 | 6
2026-01-14 | 12000.00 | 12500.00 | 12083.33 | 6
(6 rows)Take Monday 12 January. avg_7_rows averages seven trading days, which reach back to Monday 5 January: eight calendar days, because Sunday 11 January had no row. avg_7_days averages the six trading days from 6 to 12 January, a true calendar week. Neither is wrong; they answer "the last seven trading days" and "the last seven calendar days". If a closed day should count as a zero, divide the 7-day sum by 7 instead of using avg, or add the missing dates with generate_series and a LEFT JOIN first.
The date filter sits in the outer query on purpose. A WHERE day BETWEEN ... inside averaged would run before the window functions, so 8 January would lose the earlier days from its average.
Two limits to know: a RANGE frame with an offset needs exactly one ORDER BY column, of a type you can add the offset to (a date with an interval, a number with a number). And the first six rows of a ROWS frame have fewer than six rows before them, so their average covers fewer days.
Check it worked
The output has six rows with no 11 January, and on 12 January avg_7_rows is 11857.14 while avg_7_days is 13166.67. Check the second by hand: the day totals for 6, 7, 8, 9, 10 and 12 January add up to 79000, and 79000 / 6 = 13166.67.
Step 6 · Compare months and work out shares of the total
lag(x) returns x from the previous row of the window, and lead(x) from the next one. Total each month, then compare it with the month before:
WITH monthly AS (
SELECT date_trunc('month', ordered_on)::date AS month,
sum(amount) AS revenue
FROM orders
GROUP BY 1
)
SELECT month,
revenue,
lag(revenue) OVER by_month AS prev_revenue,
revenue - lag(revenue) OVER by_month AS change,
round(100 * (revenue - lag(revenue) OVER by_month) / lag(revenue) OVER by_month, 1) AS pct_change
FROM monthly
WINDOW by_month AS (ORDER BY month)
ORDER BY month; month | revenue | prev_revenue | change | pct_change
------------+-----------+--------------+-----------+------------
2026-01-01 | 308000.00 | | |
2026-02-01 | 292000.00 | 308000.00 | -16000.00 | -5.2
2026-03-01 | 295000.00 | 292000.00 | 3000.00 | 1.0
2026-04-01 | 319500.00 | 295000.00 | 24500.00 | 8.3
(4 rows)date_trunc('month', ...) turns every date into the first day of its month, and ::date drops the time it adds. January has no month before it, so lag returns NULL and everything computed from it is NULL too. That is better than a made-up zero. lag(revenue, 12) would compare with the same month last year, once you have a year of data. If a month can be missing, lag still returns the previous row, not the previous calendar month.
An empty OVER () makes the whole result one window. That is how you get each row's share of the total without a second query:
SELECT region,
sum(amount) AS revenue,
round(100 * sum(amount) / sum(sum(amount)) OVER (), 2) AS pct_of_total
FROM orders
GROUP BY region
ORDER BY revenue DESC; region | revenue | pct_of_total
--------+-----------+--------------
South | 317500.00 | 26.14
West | 310500.00 | 25.57
North | 295500.00 | 24.33
East | 291000.00 | 23.96
(4 rows)sum(sum(amount)) OVER () is the grand total, 1214500, repeated on every row. Use OVER (PARTITION BY region) instead and you get each product's share within its region.
Check it worked
February shows a change of -16000.00 and -5.2 per cent, and the four shares add up to 100.00. Check February by hand: 16000 / 308000 × 100 = 5.19, rounded to 5.2.
Step 7 · Find first and last purchases, and split customers into quartiles
first_value(x) and last_value(x) return x from the first and last rows of the frame. Find each customer's first and last product:
SELECT DISTINCT customer,
first_value(product) OVER per_customer AS first_product,
last_value(product) OVER per_customer AS last_product
FROM orders
WINDOW per_customer AS (
PARTITION BY customer
ORDER BY ordered_on, id
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
)
ORDER BY customer; customer | first_product | last_product
----------+---------------+---------------
cust-01 | Bar soap | Phone charger
cust-02 | Solar lamp | Palm oil 5 L
cust-03 | Rice 5 kg | Bar soap
cust-04 | Phone charger | Solar lamp
cust-05 | Palm oil 5 L | Garri 2 kg
cust-06 | Bar soap | Phone charger
cust-07 | Palm oil 5 L | Palm oil 5 L
cust-08 | Garri 2 kg | Rice 5 kg
cust-09 | Phone charger | Solar lamp
cust-10 | Garri 2 kg | Rice 5 kg
(10 rows)The frame line is what makes last_value work. Delete it and run the query again: you get 60 rows instead of 10. With the default frame, which stops at the current row, the "last" row is always the current row, so last_value just repeats each order's own product. first_value is unaffected because every frame starts at the first row. DISTINCT then collapses each customer's 20 or so identical rows into one, which only works once both values are the same on every row of a customer.
ntile(n) deals the rows of a window into n numbered buckets, in order, as evenly as it can. Split the ten customers into spending quartiles:
SELECT customer,
sum(amount) AS spent,
ntile(4) OVER (ORDER BY sum(amount) DESC, customer) AS quartile
FROM orders
GROUP BY customer
ORDER BY quartile, spent DESC, customer; customer | spent | quartile
----------+-----------+----------
cust-04 | 140000.00 | 1
cust-02 | 136500.00 | 1
cust-08 | 120000.00 | 1
cust-09 | 120000.00 | 2
cust-05 | 119000.00 | 2
cust-07 | 117500.00 | 2
cust-03 | 116000.00 | 3
cust-06 | 116000.00 | 3
cust-10 | 115500.00 | 4
cust-01 | 114000.00 | 4
(10 rows)Ten rows do not split into four equal groups, so the first two buckets get three customers and the last two get two. Look at cust-08 and cust-09: both spent 120000.00 but land in different quartiles. ntile splits by position, not by value, so ties can straddle a boundary. If equal spenders must share a bucket, rank them first or band them by value with CASE.
Check it worked
The first query returns 10 rows, and cust-01 first bought Bar soap and last bought a Phone charger (on 30 April). Without the frame line it returns 60 rows. The quartile query puts three customers in quartiles 1 and 2 and two in quartiles 3 and 4. Type \q to leave psql.
Step 8 · Save the report in a file and run it again
Put the four answers the shop owner asked for into one file, with a heading before each:
cat > ~/sql-window-demo/report.sql <<'SQL'
\set ON_ERROR_STOP on
\echo '1. Top three products per region (ties share a place)'
WITH ranked AS (
SELECT region, product, sum(amount) AS revenue,
rank() OVER (PARTITION BY region ORDER BY sum(amount) DESC) AS rnk
FROM orders
GROUP BY region, product
)
SELECT region, product, revenue, rnk
FROM ranked
WHERE rnk <= 3
ORDER BY region, rnk, product;
\echo '2. Revenue by month, against the month before'
WITH monthly AS (
SELECT date_trunc('month', ordered_on)::date AS month, sum(amount) AS revenue
FROM orders
GROUP BY 1
)
SELECT month, revenue,
revenue - lag(revenue) OVER by_month AS change,
round(100 * (revenue - lag(revenue) OVER by_month) / lag(revenue) OVER by_month, 1) AS pct_change
FROM monthly
WINDOW by_month AS (ORDER BY month)
ORDER BY month;
\echo '3. Share of revenue by region'
SELECT region, sum(amount) AS revenue,
round(100 * sum(amount) / sum(sum(amount)) OVER (), 2) AS pct_of_total
FROM orders
GROUP BY region
ORDER BY revenue DESC;
\echo '4. Customers by spend, in quartiles'
SELECT customer, sum(amount) AS spent,
ntile(4) OVER (ORDER BY sum(amount) DESC, customer) AS quartile
FROM orders
GROUP BY customer
ORDER BY quartile, spent DESC, customer;
SQLRun it:
sudo -u postgres psql -d shop < ~/sql-window-demo/report.sqlTo keep a copy, send the output to a file as well: sudo -u postgres psql -d shop < ~/sql-window-demo/report.sql > ~/sql-window-demo/report.txt. The file is plain text a few kilobytes long, small enough to share over a slow mobile connection. Because it starts with ON_ERROR_STOP, a mistake in any query stops the run at that query with an error and a line number.
Check it worked
The output prints the four headings, each followed by its table: 13 ranked products, 4 months ending with April at 319500.00 and 8.3 per cent, 4 regions led by South, and 10 customers ending with cust-01 in quartile 4. These are the same figures you checked step by step above.
Step 9 · Remove the practice database
When you are done, delete the database and the folder. Do this before you start the CTE tutorial too: it builds its own shop database, and createdb fails if this one still exists.
sudo -u postgres dropdb shop
rm -rf ~/sql-window-demoCheck it worked
sudo -u postgres psql -Atc "SELECT count(*) FROM pg_database WHERE datname = 'shop';"The answer is 0, and ls ~/sql-window-demo reports that the folder does not exist.
Next steps
- Split a long report query into named steps you can run one at a time:
/tutorials/break-a-long-sql-query-into-steps-with-ctes. - Go back over grouping,
HAVINGand subtotals:/tutorials/summarise-data-with-group-by-and-having. - Find out why a report query is slow and fix it with an index:
/tutorials/speed-up-slow-postgres-queries-with-explain.
Related tutorials
- Summarise data in SQL with GROUP BY, HAVING and aggregatesYou will turn twelve order rows into a PostgreSQL 18 revenue report by month and region, with subtotals, saved as a view and a CSV file that matches a hand check.
- Break a long SQL query into readable steps with CTEsYou will rewrite a 47-line nested PostgreSQL 18 report as a chain of named WITH steps you can check one at a time, read in EXPLAIN when PostgreSQL inlines a CTE and when it does not, and move old rows to an archive in one statement.
- Query a table in SQL with SELECT, WHERE and ORDER BYYou will load 500 market stall sales into PostgreSQL 18 and answer ten questions about them with SELECT, WHERE, ORDER BY, LIMIT, DISTINCT and CASE, saved in a .sql file you can run again with psql -f.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials