What this page is for

Intent: the full picture behind the quick Aggregates page. Same sections, same order, with every step table, the wrong versions, the NULL edge cases and the harder interview questions.
Read the quick page first. Each section here starts where the quick one stops.
Time: about 20 minutes.

Words you need first

Everything from the quick page (aggregate function, pile, key, NULL, HAVING), plus:

  • Primary key: the column that uniquely identifies each row, such as customers.id. No two rows share it, and it is never NULL.
  • Alias: the name you give a column or expression with AS, such as AS revenue. An alias is visible to ORDER BY, but not to WHERE or HAVING in Postgres.
  • Filler row: the one row a LEFT JOIN makes for a left-side row with no match. Its right-side columns are NULL.
  • Combined key: several columns in one GROUP BY. Together they form one key, so each pile is one unique combination.

The tables are the same food-delivery data as on the Joins page. Orders 101 to 105 have the statuses delivered, delivered, cancelled, delivered and delivered.

Why it exists

The quick page gave the reason: totals per group. Here is the mechanism behind it. A plain SELECT returns one row per input row. An aggregate with no GROUP BY squashes the whole input into one row. GROUP BY does the same squashing per pile: it sorts the rows into piles by the key and returns one row per pile. Every plain column you select has to be the same value for all rows in a pile, which is why the “must appear in the GROUP BY clause” rule exists.

Window functions differ here, because they keep every row. See Window functions.

The picture

Order lines drop through JOIN, WHERE and GROUP BY into two piles, then each pile gets one total

The same four stages as the quick page. The rest of this page zooms into each stage: the table after each step, and the wrong version that goes into each stage.

How it works, with an example

Simply: A SQL query runs its steps in a fixed order, not in the order you type them. Think of a shop counter: first you collect all the bills, then you set aside the bills you do not need with WHERE. Next, GROUP BY sorts the bills into one pile per shop, and aggregates such as sum() write one total on each pile. Last, HAVING keeps only the piles you want.

What to know: WHERE filters single rows before any piles exist, so it cannot test a total. GROUP BY makes one pile per key, and each aggregate function runs once per pile. HAVING filters the piles after the totals exist, and ORDER BY only sorts the finished rows.

The run order, one more time, with what each stage hands to the next:

FROM + JOIN   rows: one per (order, dish) pair       -> 6 lines
WHERE         rows: only the ones that pass          -> 5 lines
GROUP BY      piles: one per key value               -> 2 piles
aggregates    one value per pile (sum, count, ...)   -> 2 values
HAVING        piles: only the ones that pass         -> 0 to n piles
SELECT        columns: the ones you asked for
ORDER BY      rows: sorted, nothing added

Two facts matter most. First, WHERE cannot see piles, because piles do not exist yet. Second, the aggregate runs before HAVING, so HAVING can read the totals.

The most common mistake

GROUP BY adds nothing up

Three slips come from one idea: thinking GROUP BY does the arithmetic. It doesn’t.

  • Multiplying: sum(qty * price) multiplies inside each row, then adds per pile. GROUP BY multiplies nothing.
  • Adding: ORDER BY only sorts. ORDER BY revenue DESC puts the biggest pile first.
  • Keying by the numbers: putting qty or price in GROUP BY splits piles down to single lines, so no total forms.

The second common mistake is the difference between sum(a * b) and sum(a) * sum(b). They are not the same. Both are shown in the GROUP BY section below.

GROUP BY: one pile per key

Simply: GROUP BY sorts the rows into piles. Picture a box of receipts: you sort them into one pile per restaurant, then write one total on top of each pile. Each row goes into exactly one pile, decided by its key, which is the column named in GROUP BY. An aggregate such as sum() then gives one answer for each pile.

What to know: GROUP BY puts each row into the one pile that matches its key value, so the result has one row per pile. Aggregate functions such as sum() and count() then run once for each pile, so the key decides what one output row means.

Example: revenue per restaurant, delivered orders only. The revenue of one line is qty * price.

SQL

SELECT r.name AS restaurant, sum(oi.qty * m.price) AS revenue
FROM orders o
JOIN restaurants r ON r.id = o.restaurant_id
JOIN order_items oi ON oi.order_id = o.id
JOIN menu_items m ON m.id = oi.menu_item_id
WHERE o.status = 'delivered'
GROUP BY r.id, r.name
ORDER BY revenue DESC;

Drizzle

import { eq, desc, sql } from "drizzle-orm";
 
const revenue = sql<number>`sum(${orderItems.qty} * ${menuItems.price})`.mapWith(Number);
db.select({ restaurant: restaurants.name, revenue })
  .from(orders)
  .innerJoin(restaurants, eq(restaurants.id, orders.restaurantId))
  .innerJoin(orderItems, eq(orderItems.orderId, orders.id))
  .innerJoin(menuItems, eq(menuItems.id, orderItems.menuItemId))
  .where(eq(orders.status, 'delivered'))
  .groupBy(restaurants.id, restaurants.name)
  .orderBy(desc(revenue));

The revenue constant is a reusable SQL snippet in the code. It is not a column in any table.

After the joins (6 lines, order 103 still in):

orderrestaurantitemqty x price
101Spice HubPaneer Tikka2 x 250 = 500
101Spice HubDal Makhani1 x 200 = 200
102Dosa DenMasala Dosa3 x 120 = 360
103Burger BayClassic Burger2 x 180 = 360
104Spice HubDal Makhani2 x 200 = 400
105Spice HubPaneer Tikka1 x 250 = 250

After WHERE (5 lines, order 103 is gone because it is cancelled):

orderrestaurantitemqty x price
101Spice HubPaneer Tikka2 x 250 = 500
101Spice HubDal Makhani1 x 200 = 200
102Dosa DenMasala Dosa3 x 120 = 360
104Spice HubDal Makhani2 x 200 = 400
105Spice HubPaneer Tikka1 x 250 = 250

Piles (key = restaurants.id, restaurants.name). Note that order 101 has two lines, and both go into the Spice Hub pile. The pile is decided per line, not per order:

pile (restaurant)lines in the pilesum
Spice Hub500, 200, 400, 2501350
Dosa Den360360

Result:

restaurantrevenue
Spice Hub1350
Dosa Den360

Burger Bay is missing from the result. Its only line was removed by WHERE, so it never formed a pile. A restaurant with no rows left makes no pile at all.

Several columns make one combined key. GROUP BY restaurant_id, status is not two separate groupings. It makes one pile per pair. On the orders table:

restaurant_idstatusorders in the pilecount(*)
1delivered101, 104, 1053
2delivered1021
3cancelled1031

Passenger columns and the primary key. Every plain selected column must be grouped or aggregated. Postgres has one shortcut: grouping by a table’s primary key lets you select that table’s other columns, so GROUP BY r.id is enough for SELECT r.name. It does not extend to other tables’ columns.

The wrong versions, and what they show.

Wrong 1: the key includes the summed columns. The query groups by oi.qty and m.price as well:

restaurantqtypricerevenue
Spice Hub2250500
Spice Hub1200200
Spice Hub2200400
Spice Hub1250250
Dosa Den3120360

Five rows, and Spice Hub appears four times. Each line became its own pile, so nothing was totalled per restaurant.

Wrong 2: the key is the total. GROUP BY revenue fails in Postgres with “aggregate functions are not allowed in GROUP BY”. The total only exists after the piles are made, so it can’t define them.

Wrong 3: sum(qty) * sum(price) instead of sum(qty * price). For Spice Hub:

versioncalculationresult
right500 + 200 + 400 + 2501350
wrongsum(qty) = 6, sum(price) = 900, 6 x 9005400

The wrong version adds all quantities and all prices first, then multiplies them, which mixes lines together. It only looks right for Dosa Den (360), because that pile has one line.

Why this, not that:

  • The key is what you want one row per (a restaurant). Not o.id, which would give one row per order: the total per order, not per restaurant, so Spice Hub’s total never forms.
  • Not an aggregate (revenue), and not the summed columns (qty, price). The key has to exist before the totals do.
  • status = 'delivered' keeps the status you want. != 'cancelled' keeps every other status too, so a future status like ‘refunded’ would silently enter the total.

Trigger card

When I see “per restaurant”, “for each X” or “by Y”, I put X in GROUP BY and the sum or count in SELECT, because GROUP BY decides how many rows come out.

count(*) vs count(column)

Simply: Think of a class register. count(*) counts every line on it, even a line with blank boxes. count(column) counts only the lines where that one box has something written in it. A LEFT JOIN can add a blank line for a customer with no orders, so you count a column from the right-hand table to leave that line out.

What to know: count(*) counts rows and never looks at the values inside them. count(column) counts only the rows where that column is not NULL, and count(distinct column) counts the different non-NULL values. After a LEFT JOIN, count a column from the right-hand table.

Example: orders per customer, keeping customers who never ordered. The LEFT JOIN is the same one as on the Joins page.

SQL

SELECT c.name, count(*) AS all_rows, count(o.id) AS order_count
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name;

Drizzle

db.select({ name: customers.name, allRows: count(), orderCount: count(orders.id) })
  .from(customers)
  .leftJoin(orders, eq(orders.customerId, customers.id))
  .groupBy(customers.id, customers.name);

In Drizzle, count() with no argument is count(*).

After the LEFT JOIN (6 rows). Arjun has no order, so the join gives him one filler row with NULL in o.id:

c.idnameo.id
1Riya101
1Riya103
1Riya105
2Kabir102
3Meera104
4ArjunNULL

Piles (key = customer):

customerrows in the pilecount(*)count(o.id)
Riya333
Kabir111
Meera111
Arjun1 (the filler row)1 (wrong)0 (right)

Result: Riya 3, Kabir 1, Meera 1, Arjun 0.

The three counts, side by side:

functioncountsNULL in the columnon the orders table
count(*)rowscounted (it is one row)5
count(column)rows where the column is not NULLskippedcount(customer_id) = 5
count(distinct column)different non-NULL valuesskippedcount(distinct customer_id) = 3 (customers 1, 2, 3)

count(1) behaves like count(*). For Riya, count(distinct restaurant_id) is 2, because her orders went to restaurants 1 and 3.

Empty input. count(*) over zero rows returns 0. Sum, avg, min and max over zero rows return NULL. This matters when a report must show 0 instead of an empty cell: use coalesce(sum(...), 0).

Why this, not that:

  • After a LEFT JOIN, count a column from the right table (count(o.id)), not count(*). The filler row has NULL there, so it is skipped.
  • Use count(distinct x) when you want “how many different x”, such as customers who ordered.

Trigger card

When I see a left join followed by a count, I count a column from the right table (count(orders.id)), because the filler row for “no match” would make count(*) say 1 instead of 0.

WHERE vs HAVING

Simply: WHERE is a check at the door. It looks at each row alone, as it comes in, and drops the rows that fail, before any grouping happens. HAVING is a check after the piles are totalled. It looks at each pile’s total, such as a customer with at least two deliveries, and drops the piles that fail.

What to know: WHERE filters single rows before grouping, so it cannot use an aggregate such as count() or sum(). HAVING filters the piles after grouping and aggregating, so it can test those totals. A filter on one row’s own value goes in WHERE, and a filter on a total goes in HAVING.

Example: customers with 2 or more delivered orders.

SQL

SELECT c.name AS customer, count(o.id) AS delivered_orders
FROM customers c
JOIN orders o ON o.customer_id = c.id
WHERE o.status = 'delivered'
GROUP BY c.id, c.name
HAVING count(o.id) >= 2;

Drizzle

db.select({ customer: customers.name, deliveredOrders: count(orders.id) })
  .from(customers)
  .innerJoin(orders, eq(orders.customerId, customers.id))
  .where(eq(orders.status, 'delivered'))
  .groupBy(customers.id, customers.name)
  .having(sql`count(${orders.id}) >= 2`);

After the join (5 rows, order 103 still in):

ordercustomerstatus
101Riyadelivered
102Kabirdelivered
103Riyacancelled
104Meeradelivered
105Riyadelivered

After WHERE (4 rows). WHERE checks each row alone, so 103 goes:

ordercustomerstatus
101Riyadelivered
102Kabirdelivered
104Meeradelivered
105Riyadelivered

Piles (key = customer, counted after WHERE):

customerorders in the pilecount(o.id)
Riya101, 1052
Kabir1021
Meera1041

After HAVING count(o.id) >= 2 (piles checked after totalling):

customerdelivered_orders
Riya2

Result: Riya, 2. Kabir and Meera are removed because their piles have 1 order each.

Why it can’t be a WHERE. WHERE count(o.id) >= 2 fails in Postgres with “aggregate functions are not allowed in WHERE”. WHERE runs before GROUP BY, so there are no piles to count. HAVING runs after, so it can see the counts.

Plain columns in HAVING. HAVING o.status = 'delivered' is legal only when status is grouped, but the right place is WHERE: it removes rows before grouping.

The wrong version: grouping by orders.id. The query looks similar, but the key is the thing counted:

ordercustomerpilescount(o.id)HAVING >= 2
101Riyaone pile1removed
102Kabirone pile1removed
104Meeraone pile1removed
105Riyaone pile1removed

Each pile holds one order, so no pile reaches 2, and the result is empty. The rule: group by what you count per (the customer), never by the things you count (the orders).

Why this, not that:

  • A filter on one row’s own value (status, city) goes in WHERE. A filter on a total (count, sum, avg) goes in HAVING.
  • WHERE count(...) fails. Postgres reports it as an error, so you notice it straight away.

Trigger card

When the filter is about a total (count, sum, avg), it goes in HAVING. When it is about one row’s own value (status, city), it goes in WHERE, because WHERE runs before grouping and HAVING runs after.

Say it in an interview

Start with the 60-second answer from the quick page. If they push deeper, add one of these:

  • Order of execution: “WHERE sees rows, HAVING sees piles. That’s why an aggregate in WHERE is an error, and why aliases from SELECT aren’t visible in either of them in Postgres.”
  • Counting: “I use count(*) to count rows and count(column) when NULLs should not count. After a LEFT JOIN, I count the right-side primary key, so the filler row doesn’t count.”
  • The arithmetic: “Aggregates work per pile, and the expression inside them is computed per row. sum(qty * price) is not sum(qty) * sum(price).”

Questions interviewers ask

The eight from the quick page, plus these harder ones. Tap a question to see the answer.

Mental map

Aggregates mental map

The same map as the quick page. Each branch is a section above.

Watch

Alex The Analyst, about 12 minutes: GROUP BY and aggregate functions, in PostgreSQL, the same dialect as this page.

Alex The Analyst, about 4 minutes: HAVING in PostgreSQL, the filter on piles.