SQL Group By
On this page
SQL GROUP BY
The GROUP BY statement groups rows that have the same values into summary rows. It is typically used with aggregate functions such as COUNT(), SUM(), AVG(), MIN(), and MAX().
Basic Syntax
SELECT column_name, AGGREGATE_FUNCTION(column_name) FROM table_name GROUP BY column_name;
Example: Count Customers per Country
SELECT country, COUNT(*) AS total_customers FROM customers GROUP BY country;
Example: Total Sales per Category
SELECT category, SUM(price * quantity) AS total_sales FROM order_items GROUP BY category;
Example: Average Price per Category
SELECT category, ROUND(AVG(price), 2) AS average_price FROM products GROUP BY category;
GROUP BY with ORDER BY
ORDER BY is often used to sort grouped results (for example, highest totals first).
SELECT country, COUNT(*) AS total_customers FROM customers GROUP BY country ORDER BY total_customers DESC;
Important Rule
When using GROUP BY, every selected column must either:
- appear in the GROUP BY clause, or
- be used inside an aggregate function
Filtering: WHERE vs HAVING
WHERE filters rows before grouping. HAVING filters groups after aggregation.
HAVING is covered in detail in the next lesson.
Example: Filter Before Grouping
SELECT country, COUNT(*) AS total_customers FROM customers WHERE status = 'active' GROUP BY country;
Common Mistakes
- Selecting non-aggregated columns without adding them to GROUP BY
- Using WHERE to filter aggregated results (use HAVING instead)
- Forgetting ORDER BY when you want sorted summary output
Next Step
Continue with SQL HAVING to learn how to filter grouped results.