GROUP BY
In one line
GROUP BY groups rows that share the same value in specified columns, so aggregate functions compute a result per group.
In simple words
GROUP BY divides rows into groups based on the values in one or more columns, then applies aggregate functions to each group separately. This lets you answer questions like "how many orders did each user place?" or "what is the average salary per department?"
When you use GROUP BY, every column in the SELECT that is not inside an aggregate function must appear in the GROUP BY clause. This is because the database needs to know how to group the non-aggregated columns.
To filter groups (after aggregation), use HAVING — WHERE filters rows before grouping, HAVING filters groups after.
Example
-- Number of orders and total per user
SELECT user_id, COUNT(*) AS order_count, SUM(total) AS total_spent
FROM orders
GROUP BY user_id;Rows are grouped by user_id, then COUNT and SUM are computed for each group.
Related terms
Related Resources
Related Lessons
- GROUP BY
Learn how to group and aggregate data.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.