Why it happens: GROUP BY leaves a column ungrouped
WITH sales(category, product, amount) AS (
VALUES ('Audio', 'Headphones', 40),
('Audio', 'Speaker', 90),
('Office', 'Keyboard', 60)
)
SELECT category,
product,
SUM(amount) AS total
FROM sales
GROUP BY category;The group Audio contains two products. Which one should the column productshow? PostgreSQL generally rejects an ungrouped reference that is not functionally dependent; MySQL with ONLY_FULL_GROUP_BY (on by default) applies an equivalent check. SQLite allows “bare” columns and may pick a value from any row in the group, so accepting the query does not make that product a stable description of the group.
How to fix it in SQL
One row per category
WITH sales(category, product, amount) AS (
VALUES ('Audio', 'Headphones', 40),
('Audio', 'Speaker', 90),
('Office', 'Keyboard', 60)
)
SELECT category,
SUM(amount) AS total
FROM sales
GROUP BY category
ORDER BY category;| category | total |
|---|---|
| Audio | 130 |
| Office | 60 |
One row per category and product
If the product is part of the unit you want to analyse, include it in the grouping: GROUP BY category, product. The result will have a different granularity: one row per category-and-product pair.
How to check it
Check whether each row represents a category or a product. The number of groups should match that answer.
How to avoid it next time
A column accepted by a lenient engine can still have an undefined value.
Related cases worth checking
Some engines may allow a column that is not written out in GROUP BY if they can prove it is determined by the grouped columns, for example through a key. That rule does not justify selecting arbitrary columns. For a learner, the safest check is still to ask: “can this column have more than one value within the same group?”.