Sub topic 14
Common mistakes and how to check results
This chapter assumes you can write SELECT, WHERE, ORDER BY, INNER JOIN and LEFT JOIN, and that you know NULL means a missing value. It also assumes you have met COUNT, SUM, AVG, MIN, MAX, GROUP BY and HAVING in the earlier chapters. Here you will learn the errors that come up most often with them, how to recognize each one from its symptoms, and how to test a grouped query before you trust it.
Most aggregate bugs do not raise an error. The query runs and returns plausible numbers, and the numbers are wrong. Checking results is therefore as much a part of the work as writing the query.
Sample data for the examples
Run this setup in PostgreSQL or SQLite to follow along. The data is small so you can verify every result by hand.
CREATE TABLE customers (customer_id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER,
amount NUMERIC(10,2),
status TEXT,
shipped_at DATE
);
CREATE TABLE order_items (order_id INTEGER, product TEXT, quantity INTEGER);
INSERT INTO customers VALUES (1, 'Ada'), (2, 'Ben'), (3, 'Cy');
INSERT INTO orders VALUES
(101, 1, 100.00, 'paid', '2026-01-05'),
(102, 1, 50.00, 'refunded', NULL),
(103, 2, 300.00, 'paid', '2026-01-07'),
(104, 2, NULL, 'paid', NULL);
INSERT INTO order_items VALUES
(101, 'pen', 2), (101, 'ink', 1), (102, 'pen', 1), (103, 'pad', 3);Ada has two orders totalling 150. Ben has two orders, one with a NULL amount, totalling 300. Cy has no orders.
Mistake 1: selecting a column that is not grouped
Every column in the SELECT list of a grouped query must either appear in GROUP BY or sit inside an aggregate. The reason is that each output row represents a whole group. If a group holds several different status values, the database has no single value to show.
SELECT customer_id, status, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id;PostgreSQL rejects this with an error saying status must appear in the GROUP BY clause. Add the column to GROUP BY if you want one row per combination, or wrap it in an aggregate such as MAX(status) if you want one value per customer.
The dangerous case is a database that does not reject it. SQLite returns an arbitrary row's status for each customer. MySQL does the same when the ONLY_FULL_GROUP_BY mode is off. The query then looks fine and gives a wrong answer.
Mistake 2: aggregates in WHERE
WHERE runs before groups exist, so it cannot test an aggregate. Use HAVING for conditions on group results.
-- Fails: aggregates are not allowed in WHERE
SELECT customer_id, SUM(amount) AS total_amount
FROM orders
WHERE SUM(amount) > 100
GROUP BY customer_id;
-- Correct
SELECT customer_id, SUM(amount) AS total_amount
FROM orders
GROUP BY customer_id
HAVING SUM(amount) > 100;The opposite habit is a quieter problem. A condition on a plain column, such as HAVING status = 'paid', may work, but it filters after grouping. Put row conditions in WHERE so fewer rows reach the grouping step. In a query that groups by customer_id only, a HAVING on status can even be illegal, because status is not a grouped column.
Also avoid relying on a SELECT alias inside HAVING. PostgreSQL rejects it, MySQL and SQLite accept it. Repeat the aggregate expression for portable code.
Mistake 3: forgetting how NULL behaves
Aggregates skip NULL inputs, and this changes results in three ways.
AVG(amount)divides by the number of non-NULLvalues, not the number of rows.COUNT(column)does not count rows where the column isNULL.SUMandAVGover zero rows, or over onlyNULLvalues, returnNULL, whileCOUNTreturns 0.
SELECT customer_id,
AVG(amount) AS avg_ignoring_null,
SUM(amount) * 1.0 / COUNT(*) AS avg_per_order
FROM orders
GROUP BY customer_id;For Ben, AVG(amount) is 300 because the NULL order is skipped. The second expression gives 150 because it divides by both orders. Neither is universally right. Decide whether a missing amount means "not recorded" or "zero", and write the query to match.
To turn an empty total into zero, use COALESCE:
SELECT COALESCE(SUM(amount), 0) AS cancelled_total
FROM orders
WHERE status = 'cancelled';Without COALESCE, this query returns NULL because no rows match. Note that GROUP BY treats all NULL values in a column as one group, even though NULL = NULL is not true in a comparison.
Mistake 4: counting a LEFT JOIN with COUNT(*)
A LEFT JOIN keeps customers who have no orders by giving them one row of NULL order columns. COUNT(*) counts that placeholder row.
SELECT c.name,
COUNT(*) AS wrong_count,
COUNT(o.order_id) AS order_count
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.name;Cy shows wrong_count = 1 and order_count = 0. Count a column from the right-hand table, preferably its key.
A related trap is putting a filter on the right-hand table in WHERE. A condition like WHERE o.status = 'paid' removes the placeholder rows, so the LEFT JOIN behaves like an inner join and Cy disappears. Move the condition into the ON clause to keep customers with no matching orders.
Mistake 5: join fan-out inflates totals
When you join to a table with several matching rows, each parent row is repeated once per match. Summing a parent column afterwards counts it several times.
SELECT o.customer_id,
COUNT(*) AS inflated_count,
COUNT(DISTINCT o.order_id) AS true_count,
SUM(o.amount) AS inflated_total
FROM orders AS o
JOIN order_items AS i ON i.order_id = o.order_id
GROUP BY o.customer_id;Order 101 has two item rows, so its 100.00 is added twice. Ada's inflated_total is 250 instead of 150, and her inflated_count is 3 instead of 2. Ben's order 104 has no items, so the inner join drops it entirely.
COUNT(DISTINCT ...) repairs counts but not sums. Do not write SUM(DISTINCT o.amount) as a fix. It removes repeated amounts, so two different orders of 50.00 would collapse into one. The reliable fix is to aggregate the many-side table to one row per key before joining:
SELECT o.customer_id,
SUM(o.amount) AS total_amount,
SUM(i.item_count) AS item_count
FROM orders AS o
JOIN (SELECT order_id, SUM(quantity) AS item_count
FROM order_items
GROUP BY order_id) AS i
ON i.order_id = o.order_id
GROUP BY o.customer_id;Now each order matches exactly one row in i, so no amount is repeated.
Mistake 6: integer division in averages
Some databases, including SQL Server, return an integer when you average an integer column. AVG(quantity) over 1 and 2 gives 1, not 1.5. PostgreSQL returns a decimal for AVG but integer division still applies to expressions like SUM(quantity) / COUNT(*). Multiply by 1.0 or cast one operand, as the earlier example does.
How to check a grouped query
Use the same few checks every time.
- Reconcile with the ungrouped total. The sum of the group totals should equal the total over the whole table.
- Check the group count. The number of output rows should match
COUNT(DISTINCT grouping_column), plus one if the column can beNULL. - Inspect the extremes. Look for a
NULLgroup, an unexpected zero, or one group that is far larger than the rest. - Test one group by hand. Pick one customer and list their raw rows with a plain
SELECT ... WHERE.
The reconciliation check looks like this:
SELECT (SELECT SUM(amount) FROM orders) AS table_total,
(SELECT SUM(g.total_amount)
FROM (SELECT customer_id, SUM(amount) AS total_amount
FROM orders
GROUP BY customer_id) AS g) AS grouped_total;Both columns should be 450. If you group over a join and the two numbers differ, you have fan-out or lost rows.
Symptom guide
| Symptom | Likely cause | Fix |
|---|---|---|
| Error about a column needing `GROUP BY` | Ungrouped column in `SELECT` | Group by it or aggregate it |
| Error about aggregates in `WHERE` | Group condition in the wrong clause | Use `HAVING` |
| Customers with no orders show a count of 1 | `COUNT(*)` after `LEFT JOIN` | Count a right-side key |
| Totals larger than the table total | Join fan-out | Aggregate before joining |
| Average higher than expected | `NULL` values skipped | Decide how to treat `NULL`, use `COALESCE` |
| Total is `NULL` instead of 0 | `SUM` over no rows | `COALESCE(SUM(x), 0)` |
| Left-joined rows vanish | Right-table filter in `WHERE` | Move it to `ON` |
Exercise
A query joins orders to order_items and reports SUM(o.amount) per customer. Ada's total is 250, but the orders table shows she spent 150. Explain why, and write the corrected query's key change.
Show answer
Order 101 has two rows in orderitems, so the join repeats it twice and its 100.00 is added twice (100 + 100 + 50 = 250). The fix is to aggregate orderitems to one row per order_id in a subquery before joining, so each order matches exactly one row and SUM(o.amount) returns 150.
Exercise
You want every customer listed with their count of paid orders, including customers with none. Your query uses LEFT JOIN orders and WHERE o.status = 'paid', and Cy is missing. Why, and how do you fix it?
Show answer
The WHERE condition is false for the placeholder row with NULL columns, so Cy's row is removed after the join. Move the condition into the join: LEFT JOIN orders AS o ON o.customerid = c.customerid AND o.status = 'paid', and use COUNT(o.order_id) so Cy shows 0.