01 / 20

Avoiding Non-Aggregated
Columns in SQL

Learn why every column in your SELECT must either appear in the GROUP BY clause or be wrapped in an aggregate function.

SQL

What is Aggregation?

When you use a GROUP BY clause, SQL takes many rows and collapses them into groups. An aggregate function computes a single value from each group:

COUNT(*)
Number of rows in the group
SUM(col)
Total of all values in the group
AVG(col)
Mean average of the group
MAX / MIN
Largest or smallest value

The Core Problem

Imagine a table of students grouped by department. Each group has many student names. If you SELECT the name column without aggregating, which name should SQL pick?

department = 'CS' Alice Bob Charlie One Output Row department: 'CS' name: ??? ? 3 rows become 1 row Which name should SQL return?

Why This Matters

1
Strict SQL mode errors: Most databases (PostgreSQL, SQL Server, Oracle) will reject the query outright with a syntax error.
2
Silent wrong results: MySQL in non-strict mode may return an arbitrary value from the group: you get data that looks right but is unreliable.
3
Portability problems: A query that "works" in one database may break when migrated to another, causing production outages.

The Golden Rule

SELECT department , COUNT(*) , AVG(gpa) In GROUP BY Aggregate Aggregate FROM students GROUP BY department

Visualizing the Rule

SELECT columns In GROUP BY Inside Aggregate department year status COUNT(*) SUM(salary) AVG(gpa) ✕ Neither? ERROR! e.g., student_name without GROUP BY or aggregate

Valid vs Invalid Queries

Error
SELECT department,
       student_name,
       COUNT(*)
FROM students
GROUP BY department;
Valid
SELECT department,
       COUNT(*),
       MAX(student_name)
FROM students
GROUP BY department;

GROUP BY vs No GROUP BY

With GROUP BY Without GROUP BY
Rows returned One per group One per original row
SELECT columns Must follow the Golden Rule Any column is fine
Aggregate functions Operate within each group Not needed (optional)
Error risk High if rule is violated Low

Step-by-Step Checklist

1
Write your GROUP BY first. Decide which columns define your groups.
2
List your SELECT columns. Write out every column you want in the output.
3
Check each column: Is it in GROUP BY? If not, is it wrapped in an aggregate (COUNT, SUM, AVG, MAX, MIN)?
4
Fix violations: Either add the column to GROUP BY, or wrap it in an appropriate aggregate function.
5
Test with strict mode. Run the query on PostgreSQL or MySQL with ONLY_FULL_GROUP_BY to verify correctness.

Example 1: Simple Fix

Goal: Count students per department. Show the department name and the count.

Valid
SELECT department,      -- in GROUP BY ✓
       COUNT(*)  AS num_students  -- aggregate ✓
FROM students
GROUP BY department;
departmentnum_students
CS42
Math31
English28

Example 2: Spotting the Error

Goal: Show each department's average GPA and a student's email.

Error
SELECT department,    -- in GROUP BY ✓
       AVG(gpa),       -- aggregate ✓
       email           -- NOT in GROUP BY, NOT aggregated ✕
FROM students
GROUP BY department;

Fixes: Remove email from SELECT, add it to GROUP BY (changes the grouping!), or wrap it: MAX(email).

Example 3: Multiple GROUP BY Columns

Goal: Find total sales per store per month.

Valid
SELECT store_id,          -- in GROUP BY ✓
       sale_month,        -- in GROUP BY ✓
       SUM(amount)  AS total,  -- aggregate ✓
       COUNT(*)    AS txns   -- aggregate ✓
FROM sales
GROUP BY store_id, sale_month;

Example 4: HAVING Clause

Goal: Show departments with more than 20 students, including avg GPA.

Valid
SELECT department,
       COUNT(*)     AS num_students,
       AVG(gpa)    AS avg_gpa
FROM students
GROUP BY department
HAVING COUNT(*) > 20;

Common Mistakes

✕ Selecting a "Related" Column
Assuming city is okay because it "goes with" store_id. SQL does not know about your data relationships.
✕ Trusting MySQL Defaults
Old MySQL versions allow non-aggregated columns silently, returning arbitrary values. Never rely on this behavior.
✕ Misunderstanding Column Aliases
A column alias in SELECT doesn't change the rule. If the underlying column isn't aggregated, the alias won't save it.

Quick Reference Table

Column in SELECT In GROUP BY? In Aggregate? Result
department ✓ Yes No Valid
COUNT(*) No ✓ Yes Valid
AVG(gpa) No ✓ Yes Valid
student_name ✕ No ✕ No Error
MAX(student_name) No ✓ Yes Valid

Question 1 of 5

Which query will produce an error in strict SQL mode?

Question 2 of 5

What does the Golden Rule of GROUP BY state?

Question 3 of 5

You need to show each city and the total revenue from that city. Which query is correct?

Question 4 of 5

In MySQL with ONLY_FULL_GROUP_BY disabled, what happens when you select a non-aggregated column not in GROUP BY?

Question 5 of 5

How would you fix this query?
SELECT store_id, product_name, SUM(qty) FROM sales GROUP BY store_id