π AggregationintermediateCommonly used
How to use GROUP BY in SQL
Group rows with the same value and apply aggregate functions to each group.
Basic GROUP BYAll databases
SELECT
country,
COUNT(*) AS user_count
FROM users
GROUP BY country;Groups all rows by country and counts the users in each group.
GROUP BY multiple columnsAll databases
SELECT
country,
active,
COUNT(*) AS count
FROM users
GROUP BY country, active
ORDER BY country, active;Groups by every combination of country and active status.
GROUP BY with multiple aggregatesAll databases
SELECT
status,
COUNT(*) AS order_count,
SUM(total) AS revenue,
AVG(total) AS avg_value,
MAX(total) AS largest
FROM orders
GROUP BY status;Multiple aggregate functions on the same groups.
GROUP BY with JOINAll databases
SELECT
u.country,
COUNT(DISTINCT u.id) AS customers,
SUM(o.total) AS revenue
FROM users u
INNER JOIN orders o ON u.id = o.user_id
GROUP BY u.country
ORDER BY revenue DESC;Group revenue by country by joining users to orders first.
Common Mistakes
- βEvery column in SELECT must either be in GROUP BY or be an aggregate function
- βGROUP BY does not sort results β use ORDER BY separately