SQL GROUP BY & Aggregate Functions: COUNT, SUM, AVG, MIN, MAX Explained

πŸ“– SQL GROUP BY & Aggregate Functions: COUNT, SUM, AVG, MIN, MAX Explained

SQL GROUP BY & Aggregate Functions: When working with large datasets, you often need to summarize and analyze data rather than just retrieve individual records. SQL GROUP BY combined with aggregate functions allows you to do just that.

In this guide, you’ll learn:
βœ… What SQL GROUP BY does and when to use it
βœ… How to use COUNT, SUM, AVG, MIN, and MAX functions
βœ… Practical examples to analyze data effectively

By the end, you’ll be able to group and summarize data like a pro! πŸš€


πŸ“Œ 1. What is SQL GROUP BY?

The GROUP BY statement is used to group rows that have the same values in specified columns. It’s commonly used with aggregate functions to perform calculations on grouped data.

Syntax of GROUP BY

SELECT column_name, AGGREGATE_FUNCTION(column_name)  
FROM table_name
GROUP BY column_name;

πŸ“Œ 2. Using COUNT() to Count Records

The COUNT() function counts the number of records in a group.

Example: Count the Number of Customers in Each City

SELECT City, COUNT(*) AS Total_Customers  
FROM Customers
GROUP BY City;

Result:

CityTotal_Customers
New York3
Chicago2
Miami1

βœ… This query groups customers by city and returns the count of customers in each city.

SQL query using COUNT() to count customers per city

πŸ“Œ 3. Using SUM() to Calculate Totals

The SUM() function calculates the total sum of a column’s values.

Example: Total Sales per Customer

SELECT CustomerID, SUM(Amount) AS Total_Spent  
FROM Orders
GROUP BY CustomerID;

Result:

CustomerIDTotal_Spent
11500
21200
3800

βœ… This query groups orders by customer and returns the total amount spent by each customer.

πŸ–ΌοΈ Image Placeholder: SQL SUM() function example showing total sales per customer
πŸ“Œ Alt Tag: “SQL SUM() function calculating total sales per customer.”


πŸ“Œ 4. Using AVG() to Find Averages

The AVG() function calculates the average value of a column.

Example: Find the Average Order Amount per City

SELECT City, AVG(Amount) AS Avg_Order_Amount  
FROM Orders
JOIN Customers ON Orders.CustomerID = Customers.CustomerID
GROUP BY City;

Result:

CityAvg_Order_Amount
New York750
Chicago600
Miami800

βœ… This query groups orders by city and calculates the average order amount per city.

SQL AVG() function calculating average order amount per city.

πŸ“Œ 5. Using MIN() and MAX() to Find Extremes

  • MIN() finds the smallest value in a group.
  • MAX() finds the largest value in a group.

Example: Find the Cheapest and Most Expensive Orders per Customer

SELECT CustomerID, MIN(Amount) AS Min_Order, MAX(Amount) AS Max_Order  
FROM Orders
GROUP BY CustomerID;

Result:

CustomerIDMin_OrderMax_Order
15001000
2300900
3800800

βœ… This query groups orders by customer and returns the cheapest and most expensive orders for each customer.


πŸ“Œ 6. Filtering Grouped Data with HAVING

The HAVING clause filters grouped results, similar to WHERE, but works with aggregate functions.

Example: Find Cities with More Than 2 Customers

sqlCopyEditSELECT City, COUNT(*) AS Total_Customers  
FROM Customers  
GROUP BY City  
HAVING COUNT(*) > 2;

Result:

CityTotal_Customers
New York3

βœ… This query only returns cities with more than 2 customers.

SQL HAVING clause filtering cities with more than 2 customers.

πŸ“Œ 7. Common Mistakes to Avoid

🚫 Using WHERE Instead of HAVING for Aggregates:

-- ❌ Incorrect
SELECT City, COUNT(*) FROM Customers WHERE COUNT(*) > 2 GROUP BY City;

βœ… Fix:

SELECT City, COUNT(*) FROM Customers GROUP BY City HAVING COUNT(*) > 2;

🚫 Forgetting to Group By Non-Aggregate Columns:

-- ❌ Incorrect
SELECT City, COUNT(*) FROM Customers;

βœ… Fix:

SELECT City, COUNT(*) FROM Customers GROUP BY City;
Examples of common SQL GROUP BY mistakes and their correct versions.

πŸ“Œ Final Thoughts: Why Master GROUP BY & Aggregate Functions?

Mastering GROUP BY and aggregate functions helps in:
βœ” Analyzing business data efficiently πŸ“Š
βœ” Generating summary reports πŸ“‹
βœ” Filtering grouped results for deeper insights πŸ”

Next up in the series: “SQL Subqueries and Nested Queries: How to Write Efficient SQL Queries” – Stay tuned! πŸš€

Learn More:

Incident Management

Linux

SQL

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top