Learn how to summarize entire datasets into business metrics using COUNT, SUM, AVG, MAX, and MIN, group records cleanly with GROUP BY, filter summary groups with HAVING, and understand SQL Server's internal query execution order.
Quick Warm-Up Revision
Review these five core questions before moving into aggregations. Tap any card to check your answer.
WHEREORDER BYDISTINCTHAVING filters summary groups after
GROUP BY.
Lab Setup: CompanyDB & Employees Dataset
Run this setup script in SSMS to create CompanyDB and populate the Employees table with 10 records. Every query output in this lesson comes directly from this exact dataset.
CREATE DATABASE CompanyDB; GO USE CompanyDB; GO CREATE TABLE Employees ( EmployeeID INT PRIMARY KEY, EmployeeName VARCHAR(100), Department VARCHAR(50), Salary DECIMAL(10,2), City VARCHAR(50), Experience INT ); INSERT INTO Employees VALUES (101, 'Rahul', 'IT', 45000, 'Hyderabad', 2), (102, 'Anjali', 'HR', 35000, 'Chennai', 3), (103, 'Kiran', 'IT', 60000, 'Bangalore', 5), (104, 'Priya', 'Finance', 50000, 'Hyderabad', 4), (105, 'Arjun', 'Sales', 30000, 'Delhi', 1), (106, 'Sneha', 'IT', 70000, 'Hyderabad', 6), (107, 'Ravi', 'HR', 28000, 'Mumbai', 2), (108, 'Deepa', 'Finance', 55000, 'Chennai', 4), (109, 'Ajay', 'Sales', 40000, 'Delhi', 3), (110, 'Pooja', 'IT', 65000, 'Bangalore', 5);
Reference Table: Employees (10 Rows)
| EmployeeID | EmployeeName | Department | Salary | City | Experience |
|---|---|---|---|---|---|
| 101 | Rahul | IT | 45000.00 | Hyderabad | 2 |
| 102 | Anjali | HR | 35000.00 | Chennai | 3 |
| 103 | Kiran | IT | 60000.00 | Bangalore | 5 |
| 104 | Priya | Finance | 50000.00 | Hyderabad | 4 |
| 105 | Arjun | Sales | 30000.00 | Delhi | 1 |
| 106 | Sneha | IT | 70000.00 | Hyderabad | 6 |
| 107 | Ravi | HR | 28000.00 | Mumbai | 2 |
| 108 | Deepa | Finance | 55000.00 | Chennai | 4 |
| 109 | Ajay | Sales | 40000.00 | Delhi | 3 |
| 110 | Pooja | IT | 65000.00 | Bangalore | 5 |
AS AliasName so SSMS gives your calculated column a clean header instead of (No column name).
COUNT() and SUM()
COUNT() — Counting Rows
COUNT() returns the total number of rows matching your query.
-- Count all employees in the company SELECT COUNT(*) AS TotalEmployees FROM Employees;
| TotalEmployees |
|---|
| 10 |
Add a WHERE clause to count only rows that match a condition (for example, IT employees):
-- Count only IT employees SELECT COUNT(*) AS TotalITEmployees FROM Employees WHERE Department = 'IT';
| TotalITEmployees |
|---|
| 4 |
Matches: Rahul (101), Kiran (103), Sneha (106), and Pooja (110).
COUNT(*) vs COUNT(Column)
COUNT(*) counts every row, even if some columns contain NULL. COUNT(Salary) ignores rows where Salary is NULL.
COUNT(DISTINCT Column)
Counts only unique non-NULL values. Example: SELECT COUNT(DISTINCT City) FROM Employees; returns 5 unique cities.
SUM() — Adding Numeric Values
SUM() adds all numeric values in a column (it automatically skips NULL values and works only on numeric data types like INT, DECIMAL, and MONEY).
-- Total monthly payroll across all 10 employees SELECT SUM(Salary) AS TotalSalary FROM Employees;
| TotalSalary |
|---|
| 478000.00 |
Calculate the total salary spent exclusively on the IT department:
-- Total salary of IT department SELECT SUM(Salary) AS TotalITSalary FROM Employees WHERE Department = 'IT';
| TotalITSalary |
|---|
| 240000.00 |
Calculation: 45,000 + 60,000 + 70,000 + 65,000 = ₹2,40,000.00.
1. What does SELECT COUNT(DISTINCT Department) FROM Employees; return on our table?
2. Suppose 3 out of 10 employees have NULL in a Bonus column. What do COUNT(*) and COUNT(Bonus) return?
AVG(), MAX() and MIN()
AVG() — Finding the Average
AVG() computes the arithmetic mean (SUM / COUNT of non-NULL values) of a numeric column.
-- Company-wide average salary SELECT AVG(Salary) AS AverageSalary FROM Employees;
| AverageSalary |
|---|
| 47800.000000 |
Calculation: 478,000 / 10 = ₹47,800. SQL Server displays 6 decimal places for DECIMAL averages.
Average salary for only the Finance department:
-- Average salary of Finance department SELECT AVG(Salary) AS FinanceAvgSalary FROM Employees WHERE Department = 'Finance';
| FinanceAvgSalary |
|---|
| 52500.000000 |
Calculation: (Priya 50,000 + Deepa 55,000) / 2 = ₹52,500.
MAX() — Finding the Highest Value
MAX() returns the largest value in a column. It works on numbers, dates (most recent date), and text (last alphabetically).
-- Highest salary in the company SELECT MAX(Salary) AS HighestSalary FROM Employees; -- Highest years of experience SELECT MAX(Experience) AS HighestExperience FROM Employees;
| HighestSalary | HighestExperience |
|---|---|
| 70000.00 | 6 |
Both belong to Sneha (106, IT, Hyderabad).
MIN() — Finding the Lowest Value
MIN() returns the smallest value in a column (lowest number, earliest date, or first alphabetically).
-- Lowest salary in the company SELECT MIN(Salary) AS LowestSalary FROM Employees; -- Lowest years of experience SELECT MIN(Experience) AS LowestExperience FROM Employees;
| LowestSalary | LowestExperience |
|---|---|
| 28000.00 | 1 |
Lowest salary is Ravi (₹28,000); lowest experience is Arjun (1 year).
Pro Pattern: All 5 Aggregates in One Dashboard Query
In real analytics reports, you can combine all five aggregate functions into a single query:
SELECT COUNT(*) AS TotalEmp, SUM(Salary) AS TotalPayroll, AVG(Salary) AS AvgSalary, MIN(Salary) AS MinSalary, MAX(Salary) AS MaxSalary FROM Employees;
| TotalEmp | TotalPayroll | AvgSalary | MinSalary | MaxSalary |
|---|---|---|---|---|
| 10 | 478000.00 | 47800.000000 | 28000.00 | 70000.00 |
1. Three employees have salaries: 20,000, 40,000, and NULL. What does AVG(Salary) return?
2. Which aggregate functions can be used on text (VARCHAR) and DATE columns?
GROUP BY — Summarizing by Category
GROUP BY arranges rows with identical values into buckets (groups) so aggregate functions calculate one result per group instead of one result for the whole table.
1. Department-Wise Employee Count
SELECT Department, COUNT(*) AS TotalEmployees FROM Employees GROUP BY Department;
| Department | TotalEmployees |
|---|---|
| Finance | 2 |
| HR | 2 |
| IT | 4 |
| Sales | 2 |
2. Department-Wise Average Salary
SELECT Department, AVG(Salary) AS AverageSalary FROM Employees GROUP BY Department;
| Department | AverageSalary |
|---|---|
| Finance | 52500.000000 |
| HR | 31500.000000 |
| IT | 60000.000000 |
| Sales | 35000.000000 |
3. City-Wise Employee Count
SELECT City, COUNT(*) AS Employees FROM Employees GROUP BY City;
| City | Employees |
|---|---|
| Bangalore | 2 |
| Chennai | 2 |
| Delhi | 2 |
| Hyderabad | 3 |
| Mumbai | 1 |
4. Department-Wise Highest Salary
SELECT Department, MAX(Salary) AS HighestSalary FROM Employees GROUP BY Department;
| Department | HighestSalary |
|---|---|
| Finance | 55000.00 |
| HR | 35000.00 |
| IT | 70000.00 |
| Sales | 40000.00 |
Advanced: Multi-Column GROUP BY
You can group by two or more columns to drill down deeper (for example, headcount and total salary per City and Department combination):
SELECT City, Department, COUNT(*) AS EmpCount, SUM(Salary) AS TotalSalary FROM Employees GROUP BY City, Department ORDER BY City, Department;
| City | Department | EmpCount | TotalSalary |
|---|---|---|---|
| Bangalore | IT | 2 | 125000.00 |
| Chennai | Finance | 1 | 55000.00 |
| Chennai | HR | 1 | 35000.00 |
| Delhi | Sales | 2 | 70000.00 |
| Hyderabad | Finance | 1 | 50000.00 |
| Hyderabad | IT | 2 | 115000.00 |
| Mumbai | HR | 1 | 28000.00 |
SELECT clause must appear inside GROUP BY. Writing SELECT EmployeeName, Department, COUNT(*) FROM Employees GROUP BY Department; fails with SQL Server Error 8120 because SQL Server does not know which single EmployeeName to show for a group of 4 IT employees.
Why does SELECT City, EmployeeName, AVG(Salary) FROM Employees GROUP BY City; throw an error in SQL Server?
EmployeeName is in the SELECT list without an aggregate function and is missing from GROUP BY. A single City group like Hyderabad contains 3 different names (Rahul, Priya, Sneha), so SQL Server raises Error 8120. Fix it by either removing EmployeeName from SELECT or adding it to GROUP BY.
HAVING Clause & SQL Execution Order
HAVING filters groups created by GROUP BY based on aggregate conditions (like COUNT(*) > 2 or AVG(Salary) > 50000).
1. Departments Having More Than 2 Employees
SELECT Department, COUNT(*) AS TotalEmployees FROM Employees GROUP BY Department HAVING COUNT(*) > 2;
| Department | TotalEmployees |
|---|---|
| IT | 4 |
Finance, HR, and Sales each have 2 employees, so only IT (> 2) survives HAVING.
2. Departments with Average Salary Above ₹50,000
SELECT Department, AVG(Salary) AS AverageSalary FROM Employees GROUP BY Department HAVING AVG(Salary) > 50000;
| Department | AverageSalary |
|---|---|
| Finance | 52500.000000 |
| IT | 60000.000000 |
3. Cities Having More Than One Employee
SELECT City, COUNT(*) AS TotalEmployees FROM Employees GROUP BY City HAVING COUNT(*) > 1;
| City | TotalEmployees |
|---|---|
| Bangalore | 2 |
| Chennai | 2 |
| Delhi | 2 |
| Hyderabad | 3 |
Mumbai has only 1 employee (Ravi), so it is filtered out.
Advanced: Combining WHERE + GROUP BY + HAVING + ORDER BY
You can use both WHERE and HAVING in the same query. Watch how each step narrows down the data:
-- Among employees with 3+ years experience, find departments -- with an average salary of at least 50,000, highest first. SELECT Department, COUNT(*) AS SeniorCount, AVG(Salary) AS SeniorAvgSalary FROM Employees WHERE Experience >= 3 GROUP BY Department HAVING AVG(Salary) >= 50000 ORDER BY SeniorAvgSalary DESC;
| Department | SeniorCount | SeniorAvgSalary |
|---|---|---|
| IT | 3 | 65000.000000 |
| Finance | 2 | 52500.000000 |
Step-by-step: WHERE removes Rahul (2 yrs), Arjun (1 yr), and Ravi (2 yrs). GROUP BY computes IT = 65k, Finance = 52.5k, Sales = 40k, HR = 35k. HAVING keeps only IT and Finance. ORDER BY puts IT first.
How SQL Server Executes a Query Internally
Even though you write SELECT first, SQL Server executes clauses in this strict logical order:
Loads the source table (Employees).
Filters individual rows before grouping.
Groups remaining rows into buckets.
Filters summary groups using aggregates.
Computes final expressions & column aliases.
Sorts final rows and limits output count.
HAVING (Step 4) runs before SELECT (Step 5), you cannot write HAVING AverageSalary > 50000 in SQL Server. You must repeat the aggregate expression HAVING AVG(Salary) > 50000. However, ORDER BY (Step 6) runs after SELECT, so aliases work cleanly inside ORDER BY!
1. Why does SELECT Department, COUNT(*) AS TotalEmp FROM Employees GROUP BY Department HAVING TotalEmp > 2; fail in SQL Server?
2. Which sequence shows the correct internal execution order in SQL Server?
WHERE vs HAVING & Class Practice
| Feature | WHERE | HAVING |
|---|---|---|
| What it filters | Filters individual rows | Filters summary groups |
| Execution timing | Used before GROUP BY |
Used after GROUP BY |
| Aggregate functions | Cannot use COUNT(), SUM(), AVG() directly |
Commonly used with aggregate functions |
| Performance tip | Shrinks data early before grouping (faster) | Evaluated only on the grouped result set |
| Example | WHERE Department = 'IT' |
HAVING AVG(Salary) > 50000 |
1. You want to ignore employees earning under ₹40,000 BEFORE calculating department averages. Which clause should handle the ₹40,000 filter?
2. Which clause is valid for checking AVG(Salary) > 40000 after grouping by City?
Class Practice (10 Hands-On Queries with Outputs)
Write all 10 queries in SSMS on CompanyDB, then tap any question to verify both the SQL query and the exact expected output.
Excluding employees from Mumbai, write a single SQL query to show each City, its Employee Count, and its Average Salary — displaying only cities with at least 2 employees AND an average salary above ₹40,000, sorted from highest average salary to lowest.
0 Comments