π₯ SQL GROUP BY β Summarize Data with Aggregates
π§² Introduction β What is GROUP BY in SQL?
The GROUP BY
clause in SQL is used to group rows based on one or more columns and perform aggregate functions like SUM()
, AVG()
, COUNT()
, etc. Itβs essential for summarizing and reporting grouped data.
π― In this guide, you’ll learn:
- Syntax and structure of
GROUP BY
- Use cases with
COUNT
,SUM
,AVG
, etc. - Best practices and multiple column grouping
β 1. GROUP BY Syntax
SELECT column, AGG_FUNCTION(column)
FROM table
GROUP BY column;
β Groups the result set and performs aggregate calculations on each group.
π 2. Example β Total Orders by Customer
SELECT customer_id, COUNT(*) AS total_orders
FROM orders
GROUP BY customer_id;
β Shows how many orders each customer has placed.
π§ 3. GROUP BY Multiple Columns
SELECT region, product, SUM(sales) AS total_sales
FROM sales_data
GROUP BY region, product;
β Breaks down sales by region and product combination.
π 4. GROUP BY with Filtering (WHERE + HAVING)
SELECT department, AVG(salary) AS avg_salary
FROM employees
WHERE salary > 0
GROUP BY department
HAVING AVG(salary) > 50000;
β
Use WHERE
to pre-filter rows and HAVING
to filter grouped results.
π§© 5. GROUP BY and NULL Values
- NULL values are treated as a single group.
SELECT category, COUNT(*)
FROM products
GROUP BY category;
β NULL categories are grouped together.
π Best Practices
β Recommended | β Avoid This |
---|---|
Use meaningful column aliases | Leaving results unnamed |
Filter rows before grouping with WHERE | Filtering post-group using only HAVING |
Use consistent data types | Grouping on mixed or ambiguous types |
π Summary β Recap & Next Steps
GROUP BY
makes it easy to summarize large data sets by category. Itβs a core SQL tool for analytics and reporting.
π Key Takeaways:
- Use
GROUP BY
with aggregate functions like COUNT, SUM, AVG - Combine with
HAVING
to filter grouped results - Supports grouping on multiple columns
βοΈ Real-World Relevance:
Used in reporting tools, dashboards, KPIs, invoice summaries, and log analysis.
β‘οΈ Next: Learn about HAVING
, ROLLUP
, and CUBE
for deeper data summaries.
β FAQ β SQL GROUP BY
β What is the use of GROUP BY?
β To group rows by one or more columns for aggregate operations.
β Can I use GROUP BY without an aggregate function?
β No. GROUP BY is useful only when paired with aggregate functions.
β What happens to NULLs in GROUP BY?
β They are treated as a group.
β Can I group by multiple columns?
β
Yes, using a comma-separated list: GROUP BY col1, col2
Share Now :