Showing posts with label HAVING. Show all posts
Showing posts with label HAVING. Show all posts

GROUP BY, HAVING, and Aggregations in SQL Server Explained

Part 9: GROUP BY, HAVING, and Aggregations in SQL Server

Microsoft SQL Server Tutorial Series: Beginner to Expert


Welcome to Part 9 of our SQL Server tutorial series! In this lesson, we’ll explore how to summarize and group data using SQL Server’s powerful aggregation functions, GROUP BY and HAVING clauses.


๐ŸŽฏ What You'll Learn

  • How to group data using GROUP BY
  • How to use aggregate functions like COUNT, SUM, AVG, MIN, MAX
  • How to filter grouped results with HAVING
  • Practical examples with real-world use cases
  • Best practices for performance and clarity

๐Ÿง  What is GROUP BY?

The GROUP BY clause groups rows that have the same values in specified columns into summary rows. It's typically used with aggregate functions.

SELECT Column1, AGG_FUNCTION(Column2)
FROM TableName
GROUP BY Column1;

Example: Count students per active status:

SELECT IsActive, COUNT(*) AS TotalStudents
FROM Students
GROUP BY IsActive;

๐Ÿ“Š Common Aggregate Functions in SQL Server

Function Description Example
COUNT() Counts number of rows COUNT(*)
SUM() Total of a numeric column SUM(Marks)
AVG() Average value AVG(Fees)
MIN() Lowest value MIN(Age)
MAX() Highest value MAX(Score)

๐Ÿ“Œ Using HAVING to Filter Groups

HAVING is like WHERE, but for grouped results.

SELECT CourseID, COUNT(*) AS Enrolled
FROM Enrollments
GROUP BY CourseID
HAVING COUNT(*) > 10;

This returns only courses with more than 10 enrollments.


๐Ÿ“š Real-World Example: Students per Year

SELECT YEAR(BirthDate) AS BirthYear, COUNT(*) AS StudentCount
FROM Students
GROUP BY YEAR(BirthDate)
ORDER BY BirthYear;

This query groups students by their year of birth and counts how many students were born each year.


๐Ÿ’ก Best Practices

Practice Why It Matters
Use aliases for aggregated columns Improves readability (e.g., COUNT(*) AS Total)
Use WHERE before GROUP BY Filter raw data before grouping for performance
Use HAVING for filtering groups only HAVING is evaluated after GROUP BY
Format numbers and dates in SELECT Use FORMAT() if needed for presentation

๐Ÿงพ Quick SQL Cheat Sheet

-- Count rows per group
SELECT Department, COUNT(*) AS Total
FROM Employees
GROUP BY Department;

-- Filter groups
SELECT Category, SUM(Price) AS TotalSales
FROM Products
GROUP BY Category
HAVING SUM(Price) > 10000;
  

✅ Summary

  • Use GROUP BY to group data by columns
  • Apply aggregate functions to summarize data
  • Use HAVING to filter aggregated results
  • Combine WHERE, GROUP BY, and HAVING for full power

๐Ÿ”— What’s Next?

Was this helpful? Drop a comment or share the post to help others! ๐Ÿ™Œ

Featured Post

GROUP BY, HAVING, and Aggregations in SQL Server Explained

Part 9: GROUP BY, HAVING, and Aggregations in SQL Server Microsoft SQL Server Tutorial Series: Beginner to Expert Welcome to Part 9 of...

Popular Posts