Everyday Data Science
Latest
Agentic workflows now power a third of surveyed enterprise automationAfrica's AI startup ecosystem posts record funding yearNew benchmark results reshape the coding-agent leaderboardNigeria launches national AI strategy with major investment planRwanda's sovereign AI cloud enters public betaThe future of AI agents: from tools to teammates
Careers & SkillsTutorial

Five GROUP BY Traps That Change Your Totals Without an Error

Every query below runs clean and returns rows. Four of the five return the wrong number, and the only way to catch them is to know the ground truth first.

Ibrahim Denis FofanahIbrahim Denis FofanahData Scientist & AI Researcher9 min read·The Practical Data Analyst · Careers
Part 8 of 12The Practical Data AnalystView path →

A GROUP BY query that fails is easy to spot. The error message tells you where to look. The dangerous ones are the queries that run fine. They return rows, the numbers look plausible, and the total is wrong in a way nobody notices until a stakeholder checks the math by hand.

This piece works through five of those traps on one small table. The table has 12 orders, four customers, two products, three named regions, and two orders with no region at all. Every number in this article comes from running the queries in SQLite 3.45.1. The setup is short enough to copy and run yourself.

The setup: one table, known ground truth

CREATE TABLE orders (
  order_id INTEGER PRIMARY KEY,
  customer_id TEXT,
  region TEXT,
  product TEXT,
  qty INTEGER,
  price REAL,
  discount REAL,
  order_date TEXT
);
 
INSERT INTO orders VALUES
  (1,  'C01', 'North', 'Widget', 2,  50.0,  5.0, '2026-01-05'),
  (2,  'C01', 'North', 'Gadget', 1, 120.0, NULL, '2026-01-06'),
  (3,  'C01', 'North', 'Widget', 3,  50.0,  0.0, '2026-01-07'),
  (4,  'C02', 'North', 'Gadget', 1, 120.0, 10.0, '2026-01-08'),
  (5,  'C02', 'South', 'Widget', 4,  50.0,  5.0, '2026-01-09'),
  (6,  'C02', 'South', 'Widget', 1,  50.0,  5.0, '2026-01-10'),
  (7,  'C03', 'South', 'Gadget', 2, 120.0, 20.0, '2026-01-11'),
  (8,  'C03', 'East',  'Widget', 5,  50.0, NULL, '2026-01-12'),
  (9,  'C03', 'East',  'Gadget', 1, 120.0,  0.0, '2026-01-13'),
  (10, 'C04', 'East',  'Widget', 2,  50.0,  5.0, '2026-01-14'),
  (11, 'C04', NULL,    'Gadget', 3, 120.0, NULL, '2026-01-15'),
  (12, 'C04', NULL,    'Widget', 1,  50.0,  5.0, '2026-01-16');

Before any grouped query, pin down the ground truth. This is the number every later result gets checked against.

SELECT COUNT(*) AS n_orders, SUM(qty) AS total_qty,
       ROUND(SUM(qty*price),2) AS gross,
       ROUND(SUM(qty*price - COALESCE(discount,0)),2) AS net
FROM orders;
n_orders total_qty gross net
12 26 1860.00 1810.00

Twelve orders, 26 units, $1,860 gross, $1,810 after $50 of discounts. Four discounts are NULL, and two orders have no region. Both facts matter below.

Trap 1: COUNT(column) counts non-NULL values, not rows

SELECT COUNT(*) AS count_star, COUNT(discount) AS count_discount,
       COUNT(*) - COUNT(discount) AS null_discounts
FROM orders;
count_star count_discount null_discounts
12 8 4

COUNT(*) counts rows. COUNT(discount) counts rows where discount is not NULL. Four orders have no discount recorded, so COUNT(discount) returns 8 on a 12-order table.

This is the most common version of the trap in real work. Someone writes COUNT(email) to count users, or COUNT(discount) to count orders, and the report quietly drops every row where that column is empty. The fix is to count the thing you mean: COUNT(*) for rows, COUNT(DISTINCT customer_id) for customers, and a separate check for how many values are missing.

SELECT COUNT(*) AS n_orders,
       COUNT(DISTINCT customer_id) AS n_customers,
       COUNT(region) AS n_with_region
FROM orders;

That returns 12 orders, 4 customers, and 10 orders with a region. The gap between 12 and 10 is the next trap.

Trap 2: the average of averages is not the average

Average order value for the whole table is $1,860 divided by 12 orders, which is $155.00. Now compute it per region and average those four numbers.

SELECT region, ROUND(AVG(qty*price),2) AS avg_order_value, COUNT(*) AS n
FROM orders GROUP BY region;
region avg_order_value n
(NULL) 205.00 2
East 156.67 3
North 122.50 4
South 163.33 3
SELECT ROUND(AVG(aov),2) AS avg_of_region_aovs FROM (
  SELECT AVG(qty*price) AS aov FROM orders GROUP BY region);
avg_of_region_aovs
161.88

The average of the four regional averages is $161.88. The true overall average is $155.00. The gap is $6.88, about 4.4 percent, and it comes from weighting: the NULL region has the highest average order value at $205.00 but only 2 orders, while North has the lowest at $122.50 and the most orders at 4. Averaging the averages gives each region one vote regardless of size. The correct overall average weights each region by its order count.

The same effect shows up in the simpler average quantity per order. Regional averages are 2.00, 2.67, 1.75, and 2.33 units. Their average is 2.19. The true overall average is 26 units over 12 orders, or 2.17. The gap is small here because the group sizes are close. With uneven groups, the gap grows, and the direction depends on which group is biggest.

Trap 3: NULL forms its own group, and filters drop it silently

GROUP BY treats all NULL values as one group. Revenue by region looks like this:

SELECT region, COUNT(*) AS n, ROUND(SUM(qty*price),2) AS gross
FROM orders GROUP BY region;
region n gross
(NULL) 2 410.00
East 3 470.00
North 4 490.00
South 3 490.00

The four groups sum to $1,860, which matches the ground truth. The NULL group holds $410, which is 22 percent of revenue. Now watch what happens when a report filters to known regions, which is what most dashboards do by default:

SELECT ROUND(SUM(qty*price),2) AS gross_known_regions
FROM orders WHERE region IS NOT NULL;
gross_known_regions
1450.00

The report now says $1,450. It dropped $410 without a word. The same thing happens with WHERE region != 'North', which also excludes NULL rows because a comparison with NULL is never true. And it happens in joins: an INNER JOIN on region drops every order with no region before any aggregation runs.

The fix is to decide what the NULL group means before you filter. If unassigned orders are real revenue, label the group "Unassigned" with COALESCE(region, 'Unassigned') and keep it in the report. If they are bad data, count them separately and say so in the report, so the gap between $1,450 and $1,860 is visible instead of hidden.

Trap 4: WHERE filters rows, HAVING filters groups

Every customer in this table placed exactly 3 orders. C01 bought 6 units, C02 bought 6, C03 bought 8, C04 bought 6. Suppose the question is which customers bought more than 6 units in total. That is a question about groups, so it belongs in HAVING:

SELECT customer_id, COUNT(*) AS n_orders, SUM(qty) AS total_qty
FROM orders GROUP BY customer_id HAVING SUM(qty) > 6;
customer_id n_orders total_qty
C03 3 8

Only C03 qualifies. Now suppose someone writes the filter in WHERE instead, thinking it means the same thing:

SELECT customer_id, COUNT(*) AS n_orders, SUM(qty) AS total_qty
FROM orders WHERE qty > 2 GROUP BY customer_id;
customer_id n_orders total_qty
C01 1 3
C02 1 4
C03 1 5
C04 1 3

This answers a different question: among orders with more than 2 units, how many did each customer place. Every customer now shows 1 order, and the totals add to 15 units instead of 26. Nothing errors. The query is valid SQL answering the wrong question.

The rule is one sentence. WHERE runs before grouping and removes rows from the groups. HAVING runs after grouping and removes whole groups. The PostgreSQL documentation states it the same way: WHERE selects input rows before groups and aggregates are computed, HAVING selects group rows after.

Trap 5: a bare column in GROUP BY shows an arbitrary row

This one only bites in SQLite and MySQL with relaxed settings, which is exactly why it is dangerous: the query runs in your local database and fails in production Postgres.

SELECT region, product, SUM(qty) AS total_qty
FROM orders GROUP BY region;
region product total_qty
(NULL) Gadget 4
East Widget 8
North Widget 7
South Widget 7

Read the East row as a claim: Widget sold 8 units in the East. That claim is false. The real split, from grouping by both columns, is Widget 7 and Gadget 1. North shows Widget 7, but the real split is Widget 5 and Gadget 2. The NULL region shows Gadget 4, but the real split is Gadget 3 and Widget 1.

SELECT region, product, SUM(qty) AS total_qty
FROM orders GROUP BY region, product ORDER BY region, product;
region product total_qty
(NULL) Gadget 3
(NULL) Widget 1
East Gadget 1
East Widget 7
North Gadget 2
North Widget 5
South Gadget 2
South Widget 5

SQLite documents this directly: in an aggregate query, a bare column takes its value from an arbitrarily selected row of the group, and the choice can differ between bare columns in the same query. Most other engines refuse the query outright. PostgreSQL and MySQL with ONLY_FULL_GROUP_BY raise an error, which is the better behavior: an error you can see beats a plausible wrong value.

The rule is simple. Every non-aggregated column in SELECT must appear in GROUP BY. If a query groups by region but selects product, the product value is meaningless, even when the total next to it is correct.

The safe pattern

One query, run before any report, catches four of the five traps:

SELECT region, COUNT(*) AS n, SUM(qty) AS qty,
       ROUND(SUM(qty*price),2) AS gross
FROM orders GROUP BY region;
region n qty gross
(NULL) 2 4 410.00
East 3 8 470.00
North 4 7 490.00
South 3 7 490.00

Check three things. The row counts add to 12. The quantities add to 26. The gross values add to $1,860. If any of those fail, a trap is active somewhere upstream. Then, for any average, compute it from the raw rows, never from a grouped table.

The verdict

GROUP BY is not the risky part of SQL. The risky part is the quiet rule attached to each function and clause: COUNT skips NULLs, AVG of averages ignores group sizes, NULL groups exist until a filter removes them, WHERE shrinks groups before they form, and bare columns report arbitrary rows. None of these produce an error. All five are caught the same way: know the ground truth, check the grouped totals against it, and group by every column you select.

Key takeaways

  1. COUNT(*) counts rows. COUNT(column) counts non-NULL values. On this table that is 12 versus 8, and the gap is four orders with no discount recorded.
  2. Never average a per-group average. The regional average order values average to $161.88. The true overall average is $155.00, because the regions hold different numbers of orders.
  3. NULL is its own group in GROUP BY. Here it holds $410, or 22 percent of revenue, and any filter on region drops it without warning.
  4. WHERE filters rows before grouping. HAVING filters groups after. Asking for customers with more than 6 units total needs HAVING; putting the filter in WHERE answers a different question and returns 15 units instead of 26.
  5. Every non-aggregated column in SELECT must be in GROUP BY. SQLite fills a bare column from an arbitrary row, so East showed Widget with 8 units when the real split was Widget 7 and Gadget 1.

Which of these five has bitten you in real work? Tell me the one that cost you the most time to find.

Related on Everyday Data Science: Five Subquery Traps That Return the Wrong Answer, Five JOIN Traps That Quietly Rewrite Your Numbers. One Orders Table Reported $620, $1,240 and $2,040., Window Functions Are SQL's Most Underused Feature. Five Patterns Cover Nearly Everything.

Sources: SQLite SELECT documentation, bare columns in an aggregate query, PostgreSQL documentation, aggregate functions

About the writer

Ibrahim Denis Fofanah
Ibrahim Denis Fofanah

Data Scientist & AI Researcher

3 followers

Data scientist and AI researcher at Pace University. I coined Artificial Frictional Unemployment, and built the first machine learning model for crop yield prediction in Sierra Leone. Author of Understanding Agentic AI. I write about agentic systems and applied ML, with a bias toward what actually works, and who gets left out when it doesn't.

Share

Found this useful? Passing it on to someone who builds is the best way to help the publication grow.

Built something worth sharing? Write it up for us →