Grouping with GROUP BY
GROUP BY splits your data into groups and calculates aggregates for each group separately.
Syntax
SELECT column, AGGREGATE(other_column)
FROM table
GROUP BY column;
How It Works
Without GROUP BY, aggregates calculate across ALL rows. With GROUP BY, aggregates calculate for each unique value in the grouped column.
Exercises
Loading exercise...
Loading exercise...
Loading exercise...
Loading exercise...
Loading exercise...
Rule: Select Only Grouped or Aggregated Columns
When using GROUP BY, your SELECT can only include:
- Columns in the GROUP BY clause
- Aggregate functions
This is invalid:
-- ERROR: name is not grouped or aggregated
SELECT city, name, COUNT(*) FROM users GROUP BY city;
Free Practice
Loading SQL editor...
Try:
- Price statistics (min, max, avg) per category
- User count by city, sorted alphabetically
- Total inventory value per category

