GROUP BY Grouping
The GROUP BY clause is used to group query results by one or more columns, typically used with aggregate functions. This chapter introduces how to use GROUP BY.
Basic Syntax
Simple Grouping
Result:
With Aggregate Functions
COUNT
SUM
AVG
MAX/MIN
Multi-Column Grouping
HAVING Clause
HAVING filters grouped results (WHERE filters rows before grouping).
Basic Usage
WHERE vs HAVING
Execution Order:
- FROM - Select table
- WHERE - Filter rows
- GROUP BY - Group
- HAVING - Filter groups
- SELECT - Select columns
- ORDER BY - Sort
Multiple Aggregate Functions
Group by Expression
Practical Examples
Sales Statistics
User Behavior Analysis
Common Errors
Error 1: Non-grouped Column in SELECT
Error 2: Aggregate Function in WHERE
Performance Optimization
1. Create Indexes for Group Columns
2. Filter Before Grouping
Best Practices
- Only use grouped columns or aggregates in SELECT
- Use WHERE to filter rows, HAVING to filter groups
- Create indexes for group columns
- Filter before grouping for better performance
- Use meaningful aliases
Summary
- GROUP BY: Group data by columns
- Aggregate Functions: COUNT, SUM, AVG, MAX, MIN
- HAVING: Filter grouped results
- Multi-column Grouping: Group by multiple columns
- Performance: Create indexes, filter before grouping
Next Step: Learn ALTER Tables