What is GROUP BY in SQL?
Why Interviewers Ask This
This question tests conceptual clarity. Interviewers want to hear a precise, confident definition before moving to more complex MySQL / SQL topics. It also reveals how well you can explain technical ideas to non-experts.
Answer
GROUP BY groups rows that have the same values in specified columns into summary rows, typically used with aggregate functions. Each unique combination of GROUP BY column values produces one output row. Example: SELECT category, COUNT(*) AS total, AVG(price) AS avg_price FROM products GROUP BY category; — produces one row per category with the count and average price of products in each. Rules: (1) Every column in SELECT that is not an aggregate function must appear in GROUP BY; (2) NULL values are grouped together; (3) GROUP BY is evaluated after WHERE but before HAVING and SELECT. HAVING filters grouped results (like WHERE but for aggregates): GROUP BY category HAVING COUNT(*) > 10. Difference between WHERE and HAVING: WHERE filters individual rows before grouping; HAVING filters groups after aggregation. Multi-column grouping: GROUP BY year, month — groups by each unique year-month combination. MySQL 5.7+ with ONLY_FULL_GROUP_BY mode (default) enforces the rule that non-aggregated columns must be in GROUP BY.
Common Mistake
A common mistake is memorizing definitions without understanding implications. When asked this question, go one level deeper — explain what happens when this concept is misused or ignored.