Getting the "column must appear in the GROUP BY clause or be used in an aggregate function" error in SQL? This guide explains what causes this error and how to fix it with practical examples.
What Causes This Error?
The group by error error (42803) occurs when:
- Selecting non-aggregated column without GROUP BY
- Missing column in GROUP BY clause
- Misunderstanding GROUP BY requirements
How to Fix It
- Add all non-aggregated columns to GROUP BY clause.
- Or wrap the column in an aggregate function (MAX, MIN, ANY_VALUE).
- Use window functions if you need both detail and aggregate.
- Consider if GROUP BY is even needed for your use case.
Example: Wrong vs Correct
❌ Code That Causes the Error
SELECT department, name, AVG(salary) FROM employees GROUP BY department; -- Error: column "name" must appear in GROUP BY
✅ Corrected Code
SELECT department, AVG(salary) FROM employees GROUP BY department; -- Correct: only grouped columns and aggregates in SELECT
Quick Checklist
- [ ] Verify column/table names are spelled correctly
- [ ] Check data types match expected values
- [ ] Review query syntax for missing keywords
- [ ] Ensure referenced tables/columns exist
Related SQL Errors
If you're troubleshooting SQL errors, you might also encounter: