What this page is for

Intent: turn many order rows into one answer per group (revenue per restaurant, orders per customer), then filter those groups. A very common backend interview question.
You’ll learn: aggregate functions · GROUP BY piles · count(*) vs count(column) · WHERE vs HAVING.
Time: about 7 minutes. Read Joins first, because it builds the rows used here. Every section has a longer version on the detailed Aggregates page.

Words you need first

  • Aggregate function: takes many rows and gives one value. sum() adds, count() counts, avg() averages, min() takes the smallest, max() the biggest. For the menu prices used here, min(price) is 120, max(price) is 250, avg(price) is 187.5.
  • Pile (group): all the rows that share the same key value, such as all of Spice Hub’s order lines.
  • Key: the column or columns in GROUP BY. It decides how many piles there are and what one output row means.
  • NULL: “no value”. Not zero, not an empty text. sum, avg, min, max and count(column) skip NULLs.
  • HAVING: a filter that runs after the piles are made.

The tables are the same food-delivery ones as on Joins: orders, order_items, menu_items, restaurants and customers.

Why it exists

Dashboards and interviewers ask for totals per group: revenue per restaurant, orders per customer. GROUP BY builds all those piles in one query.

The picture

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

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.

Every query runs in this order, not in the order you type it:

FROM + JOIN   combine the tables into rows
WHERE         keep the single rows that pass (no piles exist yet)
GROUP BY      make one pile per key
aggregates    sum(), count()... run once per pile
HAVING        keep the piles that pass (totals now exist)
SELECT        choose the columns to show
ORDER BY      sort the finished rows (it adds nothing up)

GROUP BY makes the piles, aggregates total each pile, and HAVING filters on those totals.

The most common mistake

GROUP BY adds nothing up

A common slip is thinking GROUP BY multiplies or adds the numbers. It only makes the piles. sum(qty * price) multiplies each line first, then adds the lines in each pile. The key is what you want one row per (a restaurant), not the numbers you add (qty, price) and not the total (revenue).

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

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));

Piles after WHERE (order 103 was cancelled, so it is gone):

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

Result: Spice Hub 1350, Dosa Den 360. Burger Bay has no pile, because its only line was removed by WHERE.

Why this, not that:

  • Key r.id, r.name gives one row per restaurant. Not o.id, which gives one row per order.
  • Not revenue, not qty, not price. The total is the answer, so it can’t be the key. qty and price are the numbers being added.
  • status = 'delivered' keeps the status you want. != 'cancelled' would also let in any future status, such as ‘refunded’.

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 with no orders (a LEFT JOIN, see Joins).

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);

Piles (key = customer):

customero.id valuescount(*)count(o.id)
Riya101, 103, 10533
Kabir10211
Meera10411
ArjunNULL (filler row)1 (wrong)0 (right)

Arjun has no orders, so the LEFT JOIN gives him one filler row with NULL in o.id. count(*) counts that row. count(o.id) skips the NULL.

Why this, not that:

  • After a LEFT JOIN, count(o.id) not count(*).
  • count(*) counts rows. count(column) counts non-NULL values. count(distinct column) counts different non-NULL values: on orders, 5, 5 and 3 (customers 1, 2, 3).
  • count(*) does not count “the NULLs”. It counts rows and never looks inside them.

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 WHERE (4 rows, 103 removed): Riya 101 and 105, Kabir 102, Meera 104.

Piles: Riya 2, Kabir 1, Meera 1.

After HAVING count(o.id) >= 2: Riya only. Result: Riya, 2.

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(o.id) >= 2 fails with “aggregate functions are not allowed in WHERE”, because WHERE runs before the piles exist.

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

“GROUP BY puts rows into piles, one per distinct key value. Aggregates like sum, count, avg, min and max run once per pile. The key is the thing you want one row per. WHERE filters rows before the piles exist, HAVING filters the piles after they are totalled. count(*) counts rows, count(column) skips NULLs.”

Questions interviewers ask

Tap a question to see the answer.

Mental map

Aggregates mental map

Watch

Alex The Analyst, about 12 minutes: GROUP BY and aggregate functions, in PostgreSQL (the dialect used on this page).

Want more? The detailed Aggregates page has the same sections with every step table, the wrong versions, NULL edge cases, and more interview questions.


← Joins · Window functions →