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.
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:
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?
Why This Matters
The Golden Rule
Visualizing the Rule
Valid vs Invalid Queries
SELECT department, student_name, COUNT(*) FROM students GROUP BY department;
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
Example 1: Simple Fix
Goal: Count students per department. Show the department name and the count.
SELECT department, -- in GROUP BY ✓ COUNT(*) AS num_students -- aggregate ✓ FROM students GROUP BY department;
| department | num_students |
|---|---|
| CS | 42 |
| Math | 31 |
| English | 28 |
Example 2: Spotting the Error
Goal: Show each department's average GPA and a student's email.
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.
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.
SELECT department, COUNT(*) AS num_students, AVG(gpa) AS avg_gpa FROM students GROUP BY department HAVING COUNT(*) > 20;
Common Mistakes
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