MySQL GROUP BY
Overview
The GROUP BY clause groups rows that have the same values into summary rows. It is often used with aggregate functions like COUNT, SUM, AVG, MIN, MAX to produce grouped summaries.
GROUP BY Syntax
Basic GROUP BY
Single Column
Multiple Columns
Aggregate Functions
COUNT
SUM
AVG
MIN and MAX
HAVING Clause
Basic HAVING
HAVING vs WHERE
| Aspect |-------------|-------|--------| | Filters | Rows before grouping | Groups after grouping | | With GROUP BY | Before group | After group | | Aggregate functions | Cannot use | Can use | | Performance | Faster | Slower |
Complex HAVING
GROUP BY with JOIN
ROLLUP
Basic ROLLUP
GROUPING() Function
CUBE
CUBE Syntax
GROUPING SETS
Basic GROUPING SETS
Equivalent ROLLUP and CUBE
DISTINCT with GROUP BY
Practical Examples
Sales Report
User Statistics
Product Analytics
Performance Considerations
Index Usage
Optimization Tips
Troubleshooting
Common Issues
Debugging
Summary
GROUP BY clause provides:
- Grouping: Group rows by column values
- Aggregates: COUNT, SUM, AVG, MIN, MAX
- HAVING: Filter groups after grouping
- Advanced Grouping: ROLLUP, CUBE, GROUPING SETS
- Performance: Use indexes on grouping columns
- Use Cases: Reports, analytics, summaries
Previous: ORDER BY
Next: JOINs