Courses / Databases for Backend Interviews / Chapter 11
Module 6 · SQL patterns: aggregation and filtering · Chapter 11 of 27
Aggregation Patterns: Tally Counts, Group Buckets and Rolling Totals
Builds on SQL Query Patterns: A Pattern Map and the Practice Schema. Next up: Filtering Patterns: Existence, Exclusion, Aggregate Filters and Top-N per Group.
Part 1 · Tally counts
Counting is the first question
Every dashboard for a delivery service starts with counts: orders today, how many were delivered, how many customers were served. Each of these is one aggregate over a set of rows.
An aggregate function reduces many rows to one value. count, sum, avg, min and max are the usual ones. Without GROUP BY the whole result is one group and you get one row. With GROUP BY you get one row per distinct value of the grouping columns, and the aggregate is computed inside each group.
The first decision in any counting query is the grain of the answer: what one output row stands for. "Orders per store" has one row per store. "Orders per store per status" has one row per pair. Choose the grain first, and the GROUP BY list follows from it. Every column in the SELECT list must be either in the GROUP BY or inside an aggregate, and PostgreSQL rejects the query otherwise. One exception: when you group by a table's primary key, its other columns are determined by that key and may appear in the SELECT list without being listed.
Counting has three flavours that are easy to confuse:
count(*)counts rows, whatever they contain.count(expression)counts the rows where the expression is not NULL.count(DISTINCT expression)counts the different non-NULL values.
Most counting bugs are one of these three used where another was meant. This lesson runs all three on one small dataset and shows what each returns when NULLs, repeats and empty groups are present.
The data for this chapter
Every pattern chapter uses the grocery delivery schema from the patterns introduction, with its own small dataset. This chapter needs cities, stores, customers, orders and order lines. It skips the products table, because the order lines carry the price that was charged. The tables are the same as in the introduction, written a little more tightly. Results are printed with the helper from the SQL chapter.
SET TIME ZONE 'Asia/Kolkata'; CREATE TABLE cities ( city_id int PRIMARY KEY, name text NOT NULL, state text NOT NULL ); CREATE TABLE stores ( store_id int PRIMARY KEY, city_id int NOT NULL REFERENCES cities (city_id), name text NOT NULL, opened_on date NOT NULL ); CREATE TABLE customers ( customer_id int PRIMARY KEY, name text NOT NULL, city_id int NOT NULL REFERENCES cities (city_id), signed_up_at timestamptz NOT NULL ); CREATE TABLE orders ( order_id int PRIMARY KEY, customer_id int NOT NULL REFERENCES customers (customer_id), store_id int NOT NULL REFERENCES stores (store_id), placed_at timestamptz NOT NULL, status text NOT NULL CHECK (status IN ('placed', 'delivered', 'cancelled')) ); CREATE TABLE order_items ( order_id int NOT NULL REFERENCES orders (order_id), product_id int NOT NULL, qty int NOT NULL, unit_price numeric(10,2) NOT NULL, PRIMARY KEY (order_id, product_id) );
The data is 15 orders across 14 days in March 2026, in four stores. Some days have two or three orders, some have none, and four orders are not delivered: two cancelled and two still placed. Those gaps and ties are what the patterns in this chapter have to handle.
INSERT INTO cities (city_id, name, state) VALUES (1, 'Pune', 'Maharashtra'), (2, 'Hyderabad', 'Telangana'), (3, 'Chennai', 'Tamil Nadu'); INSERT INTO stores (store_id, city_id, name, opened_on) VALUES (1, 1, 'Kothrud', '2024-02-10'), (2, 1, 'Viman Nagar', '2024-08-01'), (3, 2, 'Madhapur', '2024-05-15'), (4, 3, 'Adyar', '2025-01-20'); INSERT INTO customers (customer_id, name, city_id, signed_up_at) VALUES (1, 'Asha', 1, '2025-11-03 10:00'), (2, 'Ravi', 1, '2025-12-14 18:30'), (3, 'Meera', 2, '2026-01-09 09:15'), (4, 'Karthik', 2, '2026-01-21 20:00'), (5, 'Divya', 3, '2026-02-02 12:45'), (6, 'Imran', 3, '2026-02-18 08:20'), (7, 'Sunita', 1, '2026-02-25 16:10'), (8, 'Naveen', 2, '2026-03-01 11:00'), (9, 'Zoya', 3, '2026-03-04 15:30');
INSERT INTO orders (order_id, customer_id, store_id, placed_at, status) VALUES (1, 1, 1, '2026-03-01 09:10', 'delivered'), (2, 2, 1, '2026-03-01 18:20', 'delivered'), (3, 3, 3, '2026-03-02 11:00', 'delivered'), (4, 4, 3, '2026-03-02 12:30', 'cancelled'), (5, 5, 4, '2026-03-03 19:00', 'delivered'), (6, 1, 2, '2026-03-05 10:15', 'delivered'), (7, 6, 4, '2026-03-05 20:45', 'placed'), (8, 2, 1, '2026-03-05 21:30', 'delivered'), (9, 3, 3, '2026-03-07 08:05', 'delivered'), (10, 7, 2, '2026-03-07 13:40', 'delivered'), (11, 1, 1, '2026-03-08 07:30', 'cancelled'), (12, 4, 3, '2026-03-10 17:25', 'delivered'), (13, 5, 4, '2026-03-10 18:55', 'delivered'), (14, 8, 3, '2026-03-12 09:45', 'placed'), (15, 2, 1, '2026-03-14 20:05', 'delivered'); INSERT INTO order_items (order_id, product_id, qty, unit_price) VALUES (1, 1, 2, 58.00), (1, 4, 1, 640.00), (2, 2, 3, 40.00), (3, 3, 1, 95.00), (3, 6, 2, 165.00), (4, 5, 1, 245.00), (5, 4, 1, 640.00), (6, 6, 1, 165.00), (7, 7, 3, 70.00), (8, 3, 2, 95.00), (8, 8, 2, 85.00), (9, 5, 2, 245.00), (10, 1, 4, 58.00), (11, 2, 1, 40.00), (12, 6, 3, 165.00), (13, 8, 2, 85.00), (13, 1, 1, 58.00), (14, 7, 2, 70.00), (15, 4, 1, 640.00);
Long counts, wide counts
Start with orders per store per status. The grain is one row per store and status, so both columns go into GROUP BY. This is the long form: every combination that exists is one row.
SELECT store_id, status, count(*) AS orders FROM orders GROUP BY store_id, status ORDER BY store_id, status;
store_id | status | orders ---------+-----------+------- 1 | cancelled | 1 1 | delivered | 4 2 | delivered | 2 3 | cancelled | 1 3 | delivered | 3 3 | placed | 1 4 | delivered | 2 4 | placed | 1 (8 rows)
A dashboard card usually wants the wide form: one row per store with a column for each status. Two constructs produce it. The first is the FILTER clause on an aggregate, which restricts the rows that one aggregate sees.
SELECT store_id, count(*) AS orders, count(*) FILTER (WHERE status = 'delivered') AS delivered, count(*) FILTER (WHERE status = 'cancelled') AS cancelled, count(*) FILTER (WHERE status = 'placed') AS placed FROM orders GROUP BY store_id ORDER BY store_id;
store_id | orders | delivered | cancelled | placed ---------+--------+-----------+-----------+------- 1 | 5 | 4 | 1 | 0 2 | 2 | 2 | 0 | 0 3 | 5 | 3 | 1 | 1 4 | 3 | 2 | 0 | 1 (4 rows)
The second is sum(CASE WHEN ... THEN 1 ELSE 0 END), the older form that works in every database. It gives the same numbers, with one difference to watch. If you leave out the ELSE, the CASE returns NULL for rows that do not match, and sum of nothing but NULLs is NULL, not 0. Stores 2 and 4 have no cancelled orders, so their cancelled column shows NULL.
SELECT store_id, sum(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) AS delivered, sum(CASE WHEN status = 'cancelled' THEN 1 END) AS cancelled FROM orders GROUP BY store_id ORDER BY store_id;
store_id | delivered | cancelled ---------+-----------+---------- 1 | 4 | 1 2 | 2 | NULL 3 | 3 | 1 4 | 2 | NULL (4 rows)
Prefer FILTER in PostgreSQL. It reads closer to the question, and count(*) FILTER (...) returns 0, not NULL, for an empty set, as the wide table shows for store 2 and placed orders.
What COUNT does and does not count
Orders per store says nothing about customers. A store with five orders from two customers is a different store from one with five orders from five. count(DISTINCT customer_id) counts each customer once.
SELECT store_id, count(*) AS orders, count(DISTINCT customer_id) AS customers FROM orders GROUP BY store_id ORDER BY store_id;
store_id | orders | customers ---------+--------+---------- 1 | 5 | 2 2 | 2 | 2 3 | 5 | 3 4 | 3 | 2 (4 rows)
NULL is the other trap. count(*) counts the NULL row, count(x) skips it, and count(DISTINCT x) skips it and the repeats. A three-row table with the values 1, 1 and NULL shows all three.
SELECT count(*) AS all_rows, count(x) AS non_null, count(DISTINCT x) AS distinct_non_null FROM (VALUES (1), (1), (NULL)) AS t (x);
all_rows | non_null | distinct_non_null ---------+----------+------------------ 3 | 2 | 1 (1 row)
The trap that costs the most in real reports is the empty group after a LEFT JOIN. A customer with no orders still produces one joined row, with NULL on the order side. count(*) counts that row, and count(o.order_id) does not. Zoya has signed up and never ordered, and count(*) reports one order for her.
SELECT c.name, count(*) AS count_star, count(o.order_id) AS count_orders FROM customers AS c LEFT JOIN orders AS o ON o.customer_id = c.customer_id WHERE c.customer_id IN (8, 9) GROUP BY c.name ORDER BY c.name;
name | count_star | count_orders -------+------------+------------- Naveen | 1 | 1 Zoya | 1 | 0 (2 rows)
Rule of thumb: when you count what a join found on its optional side, count a column of that side. Finally, sum over zero rows is NULL, not 0, so a total that may be empty needs coalesce.
SELECT sum(qty) AS plain_sum, coalesce(sum(qty), 0) AS safe_sum, count(*) AS rows_seen FROM order_items WHERE qty > 100;
plain_sum | safe_sum | rows_seen ----------+----------+---------- NULL | 0 | 0 (1 row)
A store has three orders from two customers. What do count(*), count(customer_id) and count(DISTINCT customer_id) return for it?
Part 2 · Group buckets
Grouping by an expression
You can group by any expression, not only by a column. A bucket is a group defined by a rule: all orders in the same week, all baskets in the same size band. The rule becomes the GROUP BY expression, and everything else is the counting you already know.
Most bucket queries need the total of each order, which lives in the order lines. Rather than repeat the join in every query, this chapter saves it as a view. A view is a stored query that you use like a table. order_totals has one row per order with the sum of its line amounts.
CREATE VIEW order_totals AS SELECT o.order_id, o.store_id, o.status, o.placed_at, sum(i.qty * i.unit_price) AS total FROM orders AS o JOIN order_items AS i ON i.order_id = o.order_id GROUP BY o.order_id, o.store_id, o.status, o.placed_at;
SELECT order_id, total FROM order_totals ORDER BY order_id;
order_id | total ---------+------- 1 | 756.00 2 | 120.00 3 | 425.00 4 | 245.00 5 | 640.00 6 | 165.00 7 | 210.00 8 | 360.00 9 | 490.00 10 | 232.00 11 | 40.00 12 | 495.00 13 | 228.00 14 | 140.00 15 | 640.00 (15 rows)
Order 1, for example, is 2 packs of milk at 58 and a 5 kg rice bag at 640, which is 756. The view has the grain of an order, which is the grain every bucket query below starts from.
Two small habits help when you group by an expression. First, write the expression in the GROUP BY the same way as in the SELECT list, or PostgreSQL will complain that the selected column is not grouped. Second, PostgreSQL also lets you group by the position of an output column (GROUP BY 1) or its alias. Both are conveniences for a quick look at the data. In code that others will maintain, a position number breaks when somebody reorders the SELECT list, so use the name.
Time buckets
Reports bucket time: per day, per week, per month. date_trunc(unit, timestamp) rounds a timestamp down to the start of its unit, so every timestamp in the same week returns the same value, and grouping by it makes weekly buckets.
SELECT date_trunc('week', placed_at)::date::text AS week_start, count(*) AS orders, sum(total) AS revenue FROM order_totals GROUP BY date_trunc('week', placed_at) ORDER BY week_start;
week_start | orders | revenue -----------+--------+-------- 2026-02-23 | 2 | 876.00 2026-03-02 | 9 | 2807.00 2026-03-09 | 4 | 1503.00 (3 rows)
date_trunc('week', ...) returns a Monday, because PostgreSQL follows the ISO week. The first bucket starts on Monday 23 February, because 1 March 2026 is a Sunday, so the first week holds only two orders. If the business week starts on Sunday, shift the timestamp before you truncate. Note too that on a timestamptz, date_trunc works in the session time zone, here Asia/Kolkata, so the week and day boundaries fall at Indian midnight.
Days are even simpler: cast to date. The cast also uses the session time zone.
SELECT placed_at::date::text AS day, count(*) AS orders FROM orders GROUP BY placed_at::date ORDER BY day;
day | orders -----------+------- 2026-03-01 | 2 2026-03-02 | 2 2026-03-03 | 1 2026-03-05 | 3 2026-03-07 | 2 2026-03-08 | 1 2026-03-10 | 2 2026-03-12 | 1 2026-03-14 | 1 (9 rows)
Nine of the fourteen days appear. The days with no orders produce no group at all, which the next lesson fixes.
Value buckets
Buckets can also come from the values. A CASE expression sets the ranges by hand: small, medium and large baskets. The digit at the start of each label is a trick that makes ORDER BY put the buckets in the order you mean.
SELECT CASE WHEN total < 300 THEN '1 small (under 300)' WHEN total < 600 THEN '2 medium (300-599)' ELSE '3 large (600 and over)' END AS basket, count(*) AS orders FROM order_totals GROUP BY 1 ORDER BY 1;
basket | orders -----------------------+------- 1 small (under 300) | 8 2 medium (300-599) | 4 3 large (600 and over) | 3 (3 rows)
When the bands are equal in width, width_bucket(value, low, high, count) does the job in one call. It divides the range from low up to, but not including, high into count equal buckets and returns the bucket number from 1. Here 0 to 800 in four buckets of 200.
SELECT order_id, total, width_bucket(total, 0, 800, 4) AS bucket FROM order_totals ORDER BY order_id;
order_id | total | bucket ---------+--------+------- 1 | 756.00 | 4 2 | 120.00 | 1 3 | 425.00 | 3 4 | 245.00 | 2 5 | 640.00 | 4 6 | 165.00 | 1 7 | 210.00 | 2 8 | 360.00 | 2 9 | 490.00 | 3 10 | 232.00 | 2 11 | 40.00 | 1 12 | 495.00 | 3 13 | 228.00 | 2 14 | 140.00 | 1 15 | 640.00 | 4 (15 rows)
Order 1 at 756 falls in bucket 4, and order 11 at 40 in bucket 1. The edges need care, because the upper bound is exclusive and out-of-range values get their own numbers.
SELECT width_bucket(799.99, 0, 800, 4) AS just_below, width_bucket(800, 0, 800, 4) AS at_upper_bound, width_bucket(-1, 0, 800, 4) AS below_lower_bound;
just_below | at_upper_bound | below_lower_bound -----------+----------------+------------------ 4 | 5 | 0 (1 row)
A value of exactly 800 goes to bucket 5, outside the four you planned, and a negative value goes to bucket 0. If your data can touch the upper bound, give high a value above the maximum or handle bucket count + 1 on purpose. Group by the bucket number, then join to a label table if the bands need names.
Which should you use? CASE is clearer when the bands are uneven or have business names, as with small, medium and large. width_bucket is shorter when the bands are equal. Whichever you pick, check that every value lands in exactly one bucket: the bucket counts must add up to the row count. The three CASE buckets above hold 8, 4 and 3 orders, and 8 plus 4 plus 3 is 15, the number of orders.
Part 3 · Buckets with no gaps
Why gaps appear
A GROUP BY can only produce a group for a value that exists in the data. If no order was placed on 4 March, there is no row with that date, so the day cannot appear in the result. For a chart that is a problem: a line chart that skips the empty days misleads, and a moving average computed over the gaps is wrong.
The cure is to build the list of buckets first and join the data to it. The list is a calendar or spine: one row for every bucket that should appear, whether it has data or not. Then a LEFT JOIN from the spine to the data keeps every bucket, and the aggregate turns the missing ones into 0. In a system that reports daily for years, teams often keep the spine as a permanent calendar table with one row per day and columns such as the week start or a holiday flag. The joins stay cheap, and the definition of a business week lives in one place.
The grouped query from the last lesson showed nine days for a two-week period.
SELECT placed_at::date::text AS day, count(*) AS orders FROM orders GROUP BY placed_at::date ORDER BY day;
day | orders -----------+------- 2026-03-01 | 2 2026-03-02 | 2 2026-03-03 | 1 2026-03-05 | 3 2026-03-07 | 2 2026-03-08 | 1 2026-03-10 | 2 2026-03-12 | 1 2026-03-14 | 1 (9 rows)
A calendar from generate_series
generate_series(start, stop, step) is a set-returning function that produces a row for each value from start to stop. With dates and an interval step, it is the calendar. The query counts orders per day for the first fourteen days of March, and an empty day now appears with 0.
SELECT d::date::text AS day, count(o.order_id) AS orders FROM generate_series('2026-03-01'::date, '2026-03-14'::date, interval '1 day') AS d LEFT JOIN orders AS o ON o.placed_at::date = d::date GROUP BY d ORDER BY d;
day | orders -----------+------- 2026-03-01 | 2 2026-03-02 | 2 2026-03-03 | 1 2026-03-04 | 0 2026-03-05 | 3 2026-03-06 | 0 2026-03-07 | 2 2026-03-08 | 1 2026-03-09 | 0 2026-03-10 | 2 2026-03-11 | 0 2026-03-12 | 1 2026-03-13 | 0 2026-03-14 | 1 (14 rows)
Here d is each day of the calendar. The join condition matches an order to a day by casting placed_at to a date. Five days come back with 0: the 4th, 6th, 9th, 11th and 13th. Two checks on the result are worth the habit. The output has 14 rows, one per day of the calendar, and the counts add up to 15, the number of orders, so no order was lost or counted twice.
The same shape works for hours, weeks or months by changing the step. Two details are worth knowing. The first is the join condition. o.placed_at::date = d::date puts a cast on the column of the big table, and an index on placed_at cannot help with it. Written as a range, o.placed_at >= d AND o.placed_at < d + interval '1 day', the same join can use such an index, because the column is compared directly with the bounds. The result is identical on this data.
SELECT d::date::text AS day, count(o.order_id) AS orders FROM generate_series('2026-03-03'::date, '2026-03-06'::date, interval '1 day') AS d LEFT JOIN orders AS o ON o.placed_at >= d AND o.placed_at < d + interval '1 day' GROUP BY d ORDER BY d;
day | orders -----------+------- 2026-03-03 | 1 2026-03-04 | 0 2026-03-05 | 3 2026-03-06 | 0 (4 rows)
Here generate_series over dates with an interval step returns timestamps with a time zone, at midnight in the session time zone, which is why the range comparison with placed_at works without a cast. The second detail is that the spine need not be time. For non-time buckets, generate_series(1, 5) gives the bucket numbers of the width_bucket query from the previous lesson, so that an empty bucket still shows. Bucket 5, the overflow bucket, has no orders in this data and appears with 0.
Two traps in the join
The first trap is count(*). After a LEFT JOIN, an empty day is still one row, with NULLs on the order side. count(*) counts it and reports 1, as the next result shows for 4 and 6 March, which had no orders.
SELECT d::date::text AS day, count(*) AS wrong_count FROM generate_series('2026-03-03'::date, '2026-03-06'::date, interval '1 day') AS d LEFT JOIN orders AS o ON o.placed_at::date = d::date GROUP BY d ORDER BY d;
day | wrong_count -----------+------------ 2026-03-03 | 1 2026-03-04 | 1 2026-03-05 | 3 2026-03-06 | 1 (4 rows)
Use count(o.order_id), a column from the optional side, as in the query above. Likewise sum over a missing day is NULL, so wrap it in coalesce(..., 0) when the output feeds a chart.
The second trap is a condition on the optional side placed in the wrong clause. To total only delivered revenue per day, the status test belongs in the ON clause, because that restricts which orders join to a day. The days with nothing delivered stay, with a total of 0.
SELECT d::date::text AS day, coalesce(sum(t.total), 0) AS revenue FROM generate_series('2026-03-03'::date, '2026-03-06'::date, interval '1 day') AS d LEFT JOIN order_totals AS t ON t.placed_at::date = d::date AND t.status = 'delivered' GROUP BY d ORDER BY d;
day | revenue -----------+-------- 2026-03-03 | 640.00 2026-03-04 | 0 2026-03-05 | 525.00 2026-03-06 | 0 (4 rows)
Put the same test in WHERE instead and the empty days disappear. For an empty day, t.status is NULL, the test NULL = 'delivered' is not true, and the row is dropped. The query silently turns back into an inner join.
SELECT d::date::text AS day, coalesce(sum(t.total), 0) AS revenue FROM generate_series('2026-03-03'::date, '2026-03-06'::date, interval '1 day') AS d LEFT JOIN order_totals AS t ON t.placed_at::date = d::date WHERE t.status = 'delivered' GROUP BY d ORDER BY d;
day | revenue -----------+-------- 2026-03-03 | 640.00 2026-03-05 | 525.00 (2 rows)
Two rows instead of four, and nobody gets an error. The rule: a test on the optional side belongs in ON, unless the point of the test is to drop the unmatched rows. When a gap-filling report shows fewer rows than its calendar has days, look first for a WHERE that mentions the joined table. The same slip turns a LEFT JOIN into an inner join in any query, and it is one of the most common mistakes in reporting code.
Part 4 · Subtotals
WHERE, HAVING and grouped results
A report with totals needs filters at two levels. WHERE filters rows before grouping, so it decides what goes into the aggregates. HAVING filters groups after the aggregates exist, so it can use them. This query keeps delivered orders only, then keeps stores whose delivered revenue is over 800.
The queries in this lesson use the order_totals view from the previous lesson: one row per order with its total.
SELECT store_id, count(*) AS orders, sum(total) AS revenue FROM order_totals WHERE status = 'delivered' GROUP BY store_id HAVING sum(total) > 800 ORDER BY store_id;
store_id | orders | revenue ---------+--------+-------- 1 | 4 | 1876.00 3 | 3 | 1410.00 4 | 2 | 868.00 (3 rows)
Viman Nagar is missing, because its delivered revenue of 397 does not pass the HAVING. If the status test were in HAVING, it would still work only when status was a grouping column. The rule that keeps queries fast and clear is: a test on a plain column goes in WHERE, a test on an aggregate goes in HAVING. Putting a plain-column test in WHERE is also cheaper, because the rows are dropped before the database spends time grouping them.
The reverse mistake is to put an aggregate in WHERE. The rows of a group do not exist yet when WHERE runs, so PostgreSQL refuses the query with SQLSTATE 42803 and the fix is to move the test to HAVING.
SELECT store_id FROM order_totals WHERE sum(total) > 800 GROUP BY store_id;
ERROR 42803: aggregate functions are not allowed in WHEREROLLUP: totals by level
A finance report wants revenue per store, a subtotal per city and a grand total. You could run three queries and glue them with UNION ALL, or ask for the totals in one pass with GROUP BY ROLLUP. ROLLUP (city, store) produces the groups (city, store), (city) and the empty grouping (), which is the grand total.
SELECT c.name AS city, s.name AS store, sum(t.total) AS revenue FROM order_totals AS t JOIN stores AS s ON s.store_id = t.store_id JOIN cities AS c ON c.city_id = s.city_id WHERE t.status = 'delivered' GROUP BY ROLLUP (c.name, s.name) ORDER BY c.name, s.name;
city | store | revenue ----------+-------------+-------- Chennai | Adyar | 868.00 Chennai | NULL | 868.00 Hyderabad | Madhapur | 1410.00 Hyderabad | NULL | 1410.00 Pune | Kothrud | 1876.00 Pune | Viman Nagar | 397.00 Pune | NULL | 2273.00 NULL | NULL | 4551.00 (8 rows)
Every city has a row with the store NULL: the city subtotal. The last row, with both NULL, is the grand total, 4551. The sums add up: 1876 plus 397 is 2273 for Pune, and 868 plus 1410 plus 2273 is 4551. A ROLLUP over n columns produces the n plus 1 levels you get by dropping columns from the right. That makes the order of the columns matter. ROLLUP (city, store) gives per city and then the total, as intended. ROLLUP (store, city) would give a subtotal per store name and then the total, which is rarely what a report needs. Put the broadest level first. Written out, ROLLUP (a, b) is the same as GROUPING SETS ((a, b), (a), ()).
These NULLs are placeholders, not missing data, and they mix up with real NULLs. If a store name could be NULL, you could not tell it from a subtotal row. GROUPING(columns) settles it: it returns a bit mask where 1 means the column was aggregated away in that row.
SELECT c.name AS city, s.name AS store, sum(t.total) AS revenue, GROUPING(c.name, s.name) AS g FROM order_totals AS t JOIN stores AS s ON s.store_id = t.store_id JOIN cities AS c ON c.city_id = s.city_id WHERE t.status = 'delivered' GROUP BY ROLLUP (c.name, s.name) ORDER BY g, c.name, s.name;
city | store | revenue | g ----------+-------------+---------+-- Chennai | Adyar | 868.00 | 0 Hyderabad | Madhapur | 1410.00 | 0 Pune | Kothrud | 1876.00 | 0 Pune | Viman Nagar | 397.00 | 0 Chennai | NULL | 868.00 | 1 Hyderabad | NULL | 1410.00 | 1 Pune | NULL | 2273.00 | 1 NULL | NULL | 4551.00 | 3 (8 rows)
Labels, GROUPING SETS and CUBE
Readers do not want NULL in a report. Use GROUPING inside a CASE to print a label, and sort with GROUPING first so that subtotals follow their detail rows.
SELECT CASE WHEN GROUPING(c.name) = 1 THEN 'all cities' ELSE c.name END AS city, CASE WHEN GROUPING(s.name) = 1 THEN 'all stores' ELSE s.name END AS store, sum(t.total) AS revenue FROM order_totals AS t JOIN stores AS s ON s.store_id = t.store_id JOIN cities AS c ON c.city_id = s.city_id WHERE t.status = 'delivered' GROUP BY ROLLUP (c.name, s.name) ORDER BY GROUPING(c.name), c.name, GROUPING(s.name), s.name;
city | store | revenue -----------+-------------+-------- Chennai | Adyar | 868.00 Chennai | all stores | 868.00 Hyderabad | Madhapur | 1410.00 Hyderabad | all stores | 1410.00 Pune | Kothrud | 1876.00 Pune | Viman Nagar | 397.00 Pune | all stores | 2273.00 all cities | all stores | 4551.00 (8 rows)
ROLLUP is a shorthand for a special case of GROUPING SETS, which lists exactly the groupings you want. This query counts orders per city, per status and in total, but not per city and status together.
SELECT c.name AS city, t.status, count(*) AS orders FROM order_totals AS t JOIN stores AS s ON s.store_id = t.store_id JOIN cities AS c ON c.city_id = s.city_id GROUP BY GROUPING SETS ((c.name), (t.status), ()) ORDER BY c.name, t.status;
city | status | orders ----------+-----------+------- Chennai | NULL | 3 Hyderabad | NULL | 5 Pune | NULL | 7 NULL | cancelled | 2 NULL | delivered | 11 NULL | placed | 2 NULL | NULL | 15 (7 rows)
Each row belongs to one of the three sets: the first three are cities, the next three are statuses, and the last is the whole table. CUBE (a, b) goes further and produces every combination: (a, b), (a), (b) and (). That is the cross-tabulation with margins, the table you would draw by hand with row totals and column totals.
SELECT c.name AS city, t.status, count(*) AS orders FROM order_totals AS t JOIN stores AS s ON s.store_id = t.store_id JOIN cities AS c ON c.city_id = s.city_id GROUP BY CUBE (c.name, t.status) ORDER BY c.name, t.status;
city | status | orders ----------+-----------+------- Chennai | delivered | 2 Chennai | placed | 1 Chennai | NULL | 3 Hyderabad | cancelled | 1 Hyderabad | delivered | 3 Hyderabad | placed | 1 Hyderabad | NULL | 5 Pune | cancelled | 1 Pune | delivered | 6 Pune | NULL | 7 NULL | cancelled | 2 NULL | delivered | 11 NULL | placed | 2 NULL | NULL | 15 (14 rows)
Part 5 · Rolling totals
Running totals and the default frame
A running total adds each row to everything before it. It is a window function: sum(x) OVER (ORDER BY ...) computes a sum for each row over a set of rows related to that row, and keeps every row in the output. The set is the window frame, and the frame decides everything about a rolling calculation.
If you write ORDER BY inside the window and no frame, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. The word RANGE is the catch. It means the frame ends at the current row's last peer: every row that ties with it on the ORDER BY value. The alternative, ROWS, counts physical rows and ignores ties.
The data has ties: orders 1 and 2 are both on 1 March. Ordering the window by date only, the two orders are peers. This query puts both frames side by side.
SELECT order_id, placed_at::date::text AS day, total, sum(total) OVER (ORDER BY placed_at::date) AS running_range, sum(total) OVER (ORDER BY placed_at::date ROWS UNBOUNDED PRECEDING) AS running_rows FROM order_totals WHERE status = 'delivered' AND placed_at < '2026-03-06' ORDER BY placed_at, order_id;
order_id | day | total | running_range | running_rows ---------+------------+--------+---------------+------------- 1 | 2026-03-01 | 756.00 | 876.00 | 756.00 2 | 2026-03-01 | 120.00 | 876.00 | 876.00 3 | 2026-03-02 | 425.00 | 1301.00 | 1301.00 5 | 2026-03-03 | 640.00 | 1941.00 | 1941.00 6 | 2026-03-05 | 165.00 | 2466.00 | 2106.00 8 | 2026-03-05 | 360.00 | 2466.00 | 2466.00 (6 rows)
With RANGE, orders 1 and 2 both show 876, because the frame of order 1 already includes its peer, order 2. With ROWS, order 1 shows 756 and order 2 shows 876. The same happens on 5 March for orders 6 and 8: 2466 for both under RANGE, and 2106 then 2466 under ROWS. The ROWS column also depends on which of two tied rows the database visits first, and the query does not say. The order 756 then 876 is what this run shows, not a promise.
Making the total deterministic
Watch the scene fill the same six rows. The RANGE column jumps by a whole tie at a time, and the ROWS column grows row by row.
Watch for the two orders that share a date: o1 and o2 on 1 March
Read it as steps
Orders 1 and 2 share a date, and so do 6 and 8; RANGE gives both rows of a tie the same total, ROWS does not.
Neither is wrong, but only one is what a reader of a statement expects: a balance that moves with every transaction. The usual fix is to make the order total, so that no two rows tie: add a unique column to the ORDER BY, such as order_id. With no ties, RANGE and ROWS agree. For clarity, say ROWS as well.
SELECT order_id, placed_at::date::text AS day, total, sum(total) OVER (ORDER BY placed_at::date, order_id) AS running FROM order_totals WHERE status = 'delivered' AND placed_at < '2026-03-06' ORDER BY placed_at, order_id;
order_id | day | total | running ---------+------------+--------+-------- 1 | 2026-03-01 | 756.00 | 756.00 2 | 2026-03-01 | 120.00 | 876.00 3 | 2026-03-02 | 425.00 | 1301.00 5 | 2026-03-03 | 640.00 | 1941.00 6 | 2026-03-05 | 165.00 | 2106.00 8 | 2026-03-05 | 360.00 | 2466.00 (6 rows)
Moving averages with ROWS
A moving average averages the last n days. It uses a frame of its own: ROWS BETWEEN 6 PRECEDING AND CURRENT ROW is the current row and the six before it, so seven rows. For a calendar with one row per day, that is a 7-day average. This uses a daily view, a calendar with revenue from delivered orders and 0 for empty days.
CREATE VIEW daily AS SELECT d::date AS day, coalesce(sum(t.total) FILTER (WHERE t.status = 'delivered'), 0) AS revenue FROM generate_series('2026-03-01'::date, '2026-03-14'::date, interval '1 day') AS d LEFT JOIN order_totals AS t ON t.placed_at::date = d::date GROUP BY d;
SELECT day::text AS day, revenue, round(avg(revenue) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW), 1) AS avg_7d, count(*) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS days_seen FROM daily ORDER BY day;
day | revenue | avg_7d | days_seen -----------+---------+--------+---------- 2026-03-01 | 876.00 | 876.0 | 1 2026-03-02 | 425.00 | 650.5 | 2 2026-03-03 | 640.00 | 647.0 | 3 2026-03-04 | 0 | 485.3 | 4 2026-03-05 | 525.00 | 493.2 | 5 2026-03-06 | 0 | 411.0 | 6 2026-03-07 | 722.00 | 455.4 | 7 2026-03-08 | 0 | 330.3 | 7 2026-03-09 | 0 | 269.6 | 7 2026-03-10 | 723.00 | 281.4 | 7 2026-03-11 | 0 | 281.4 | 7 2026-03-12 | 0 | 206.4 | 7 2026-03-13 | 0 | 206.4 | 7 2026-03-14 | 640.00 | 194.7 | 7 (14 rows)
The first six days have fewer than seven rows in the frame. The column days_seen counts the rows inside the frame, and the average on day 1 is just day 1. If a half-empty window is wrong for your report, filter those rows out or return NULL until days_seen reaches 7. From day 7 on, the frame is full. The scene shows the window growing and then sliding.
Watch for the window: it holds at most seven days of revenue
Read it as steps
ROWS against RANGE on missing days
The previous query relied on a gap-free calendar. If you compute the average over the sparse list of days that have orders, ROWS 2 PRECEDING covers the last three rows, whatever dates they hold. RANGE with an interval covers the last three days by date, and works when the calendar has holes.
SELECT day::text AS day, revenue, round(avg(revenue) OVER (ORDER BY day ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 1) AS rows_3, round(avg(revenue) OVER (ORDER BY day RANGE BETWEEN INTERVAL '2 days' PRECEDING AND CURRENT ROW), 1) AS range_3d FROM daily WHERE revenue > 0 ORDER BY day;
day | revenue | rows_3 | range_3d -----------+---------+--------+--------- 2026-03-01 | 876.00 | 876.0 | 876.0 2026-03-02 | 425.00 | 650.5 | 650.5 2026-03-03 | 640.00 | 647.0 | 647.0 2026-03-05 | 525.00 | 530.0 | 582.5 2026-03-07 | 722.00 | 629.0 | 623.5 2026-03-10 | 723.00 | 656.7 | 723.0 2026-03-14 | 640.00 | 695.0 | 640.0 (7 rows)
On 5 March the two frames differ. rows_3 averages the last three rows (2, 3 and 5 March), while range_3d averages the rows dated 3 to 5 March, which are only two. On 10 March the row-based window reaches back to 5 March, five days earlier, and the range window sees only itself. A RANGE frame with an interval needs a single ORDER BY column of a date, time or numeric type.
Missing days also change what a 7-day average means. Here is the average for 14 March, computed twice with the same ROWS BETWEEN 6 PRECEDING AND CURRENT ROW frame: once over only the days that have revenue, and once over the full calendar.
WITH sparse AS ( SELECT day, round(avg(revenue) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW), 1) AS avg_sparse FROM daily WHERE revenue > 0 ), full_cal AS ( SELECT day, round(avg(revenue) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW), 1) AS avg_calendar FROM daily ) SELECT day::text AS day, avg_sparse, avg_calendar FROM sparse JOIN full_cal USING (day) WHERE day = '2026-03-14';
day | avg_sparse | avg_calendar -----------+------------+------------- 2026-03-14 | 650.1 | 194.7 (1 row)
Only seven days have revenue in the whole fortnight, so the sparse frame covers all of them, from 1 March to 14 March, and averages 4551 over 7 rows to give 650.1. The calendar frame covers 8 to 14 March, counts the empty days as zero, and gives 194.7. Both are correct answers to different questions, and only the second is an average per day over the last seven days. A moving average over a list with holes silently answers the first one.
Part 6 · Share of total and practice
Percent of the whole
A share is a part divided by a whole, and the whole is itself an aggregate. A window function with an empty OVER () computes an aggregate over all rows and attaches it to each row, so the part and the whole sit on the same line. The queries in this lesson use the order_totals view from the group-buckets lesson.
Windows run after GROUP BY, so you can use an aggregate inside a window function. sum(sum(total)) OVER () is the sum, over all groups, of each group's sum. Here is each store's share of delivered revenue.
SELECT s.name AS store, sum(t.total) AS revenue, round(100 * sum(t.total) / sum(sum(t.total)) OVER (), 1) AS pct_of_all FROM order_totals AS t JOIN stores AS s ON s.store_id = t.store_id WHERE t.status = 'delivered' GROUP BY s.name ORDER BY revenue DESC;
store | revenue | pct_of_all ------------+---------+----------- Kothrud | 1876.00 | 41.2 Madhapur | 1410.00 | 31.0 Adyar | 868.00 | 19.1 Viman Nagar | 397.00 | 8.7 (4 rows)
Adding PARTITION BY makes the whole a subgroup: this gives each store's share of its own city. The two Pune stores split Pune, and the other cities have one store each, so 100.
SELECT c.name AS city, s.name AS store, sum(t.total) AS revenue, round(100 * sum(t.total) / sum(sum(t.total)) OVER (PARTITION BY c.name), 1) AS pct_of_city FROM order_totals AS t JOIN stores AS s ON s.store_id = t.store_id JOIN cities AS c ON c.city_id = s.city_id WHERE t.status = 'delivered' GROUP BY c.name, s.name ORDER BY c.name, s.name;
city | store | revenue | pct_of_city ----------+-------------+---------+------------ Chennai | Adyar | 868.00 | 100.0 Hyderabad | Madhapur | 1410.00 | 100.0 Pune | Kothrud | 1876.00 | 82.5 Pune | Viman Nagar | 397.00 | 17.5 (4 rows)
Mind the arithmetic. Division of two integers truncates, so a share written as count(*) / total is 0 for any part smaller than the whole. Make one side numeric by multiplying by 100.0 or dividing by 3.0, as the next query shows.
SELECT 1 / 3 AS integer_division, 1 / 3.0 AS numeric_division, round(100 * 1 / 3.0, 1) AS percent;
Practice problems
Three problems that use everything in this chapter. Try each before you read the solution. All run on the data above.
Problem 1. For each store, the percentage of its orders that were cancelled, to one decimal place. The trap is integer division.
SELECT store_id, count(*) AS orders, count(*) FILTER (WHERE status = 'cancelled') AS cancelled, round(100.0 * count(*) FILTER (WHERE status = 'cancelled') / count(*), 1) AS cancelled_pct FROM orders GROUP BY store_id ORDER BY store_id;
store_id | orders | cancelled | cancelled_pct ---------+--------+-----------+-------------- 1 | 5 | 1 | 20.0 2 | 2 | 0 | 0.0 3 | 5 | 1 | 20.0 4 | 3 | 0 | 0.0 (4 rows)
The 100.0 forces numeric division. Stores 1 and 3 each cancelled 1 of 5, which is 20.0, and stores with none show 0.0 instead of NULL, because the FILTER count of an empty set is 0.
Problem 2. For two stores, delivered orders with a running revenue that restarts for each store. PARTITION BY restarts the total, and the explicit ROWS frame with a tiebreaker makes it deterministic.
SELECT s.name AS store, order_id, total, sum(total) OVER (PARTITION BY t.store_id ORDER BY t.placed_at, t.order_id ROWS UNBOUNDED PRECEDING) AS store_running FROM order_totals AS t JOIN stores AS s ON s.store_id = t.store_id WHERE t.status = 'delivered' AND t.store_id IN (1, 3) ORDER BY s.name, t.placed_at, t.order_id;
store | order_id | total | store_running ---------+----------+--------+-------------- Kothrud | 1 | 756.00 | 756.00 Kothrud | 2 | 120.00 | 876.00 Kothrud | 8 | 360.00 | 1236.00 Kothrud | 15 | 640.00 | 1876.00 Madhapur | 3 | 425.00 | 425.00 Madhapur | 9 | 490.00 | 915.00 Madhapur | 12 | 495.00 | 1410.00 (7 rows)
Each store's last running total matches its delivered revenue in the subtotal report: 1876 for Kothrud and 1410 for Madhapur. That is a good cross-check for a rolling query: its last row should equal the plain aggregate. Notice also that Madhapur starts again at its own first order: the partition restarted the running total, which an unpartitioned window would not do.
A third problem, and what to check
Problem 3. For each day that has delivered revenue, the day's share of the total and the cumulative revenue. Aggregate to days in a subquery first, because windows run after grouping, then apply two windows to it, one empty and one ordered.
SELECT d.day::text AS day, d.revenue, round(100.0 * d.revenue / sum(d.revenue) OVER (), 1) AS pct, sum(d.revenue) OVER (ORDER BY d.day) AS cumulative FROM ( SELECT placed_at::date AS day, sum(total) AS revenue FROM order_totals WHERE status = 'delivered' GROUP BY placed_at::date ) AS d ORDER BY d.day;
day | revenue | pct | cumulative -----------+---------+------+----------- 2026-03-01 | 876.00 | 19.2 | 876.00 2026-03-02 | 425.00 | 9.3 | 1301.00 2026-03-03 | 640.00 | 14.1 | 1941.00 2026-03-05 | 525.00 | 11.5 | 2466.00 2026-03-07 | 722.00 | 15.9 | 3188.00 2026-03-10 | 723.00 | 15.9 | 3911.00 2026-03-14 | 640.00 | 14.1 | 4551.00 (7 rows)
The shares add to 100 apart from rounding: 19.2 plus 9.3 plus 14.1 plus 11.5 plus 15.9 plus 15.9 plus 14.1 is 100. The last cumulative value, 4551, is the grand total from the ROLLUP, so three different queries agree. When two independently written queries agree on a total, the chance that both are wrong in the same way is small, which is why this check is worth making a habit.
A window function cannot filter rows by itself. Written in WHERE, it fails with SQLSTATE 42P20, because windows are computed after WHERE has chosen the rows. That is why the problem above first reduces the table to days in a subquery, and applies the windows in the outer query.
SELECT order_id FROM order_totals WHERE sum(total) OVER () > 1000;
ERROR 42P20: window functions are not allowed in WHERE
Before you trust an aggregation query, run through five checks: the grain of the output, the NULL and empty-group behaviour of each aggregate, whether a LEFT JOIN hides a count(*) mistake, whether ties change a window result, and whether a total matches a simpler query over the same rows.
Why does count(*) / total_orders return 0 for each store?
- Both sides are integers, and integer division truncates, so any fraction below 1 becomes 0.
All chapters · Previous: SQL Query Patterns: A Pattern Map and the Practice Schema