SQL Server Day 3 & Day 4

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.

SELECT * FROM Employees;
WHERE
ORDER BY
DISTINCT
WHERE filters individual rows before grouping.
HAVING 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
101RahulIT45000.00Hyderabad2
102AnjaliHR35000.00Chennai3
103KiranIT60000.00Bangalore5
104PriyaFinance50000.00Hyderabad4
105ArjunSales30000.00Delhi1
106SnehaIT70000.00Hyderabad6
107RaviHR28000.00Mumbai2
108DeepaFinance55000.00Chennai4
109AjaySales40000.00Delhi3
110PoojaIT65000.00Bangalore5
[What Are Aggregate Functions?]: Aggregate functions take multiple rows as input and collapse them into a single summary value (such as a count, total, average, maximum, or minimum). Always use 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;
Output1 row returned
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';
Output1 row returned
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;
Output1 row returned
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';
Output1 row returned
TotalITSalary
240000.00

Calculation: 45,000 + 60,000 + 70,000 + 65,000 = ₹2,40,000.00.

Class Pop Quiz #1

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;
Output1 row returned
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';
Output1 row returned
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;
Outputs2 result sets
HighestSalaryHighestExperience
70000.006

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;
Outputs2 result sets
LowestSalaryLowestExperience
28000.001

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;
Output1 summary row
TotalEmpTotalPayrollAvgSalaryMinSalaryMaxSalary
10478000.0047800.00000028000.0070000.00
Class Pop Quiz #2

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;
Output4 rows returned
DepartmentTotalEmployees
Finance2
HR2
IT4
Sales2

2. Department-Wise Average Salary

SELECT Department,
       AVG(Salary) AS AverageSalary
FROM Employees
GROUP BY Department;
Output4 rows returned
DepartmentAverageSalary
Finance52500.000000
HR31500.000000
IT60000.000000
Sales35000.000000

3. City-Wise Employee Count

SELECT City,
       COUNT(*) AS Employees
FROM Employees
GROUP BY City;
Output5 rows returned
CityEmployees
Bangalore2
Chennai2
Delhi2
Hyderabad3
Mumbai1

4. Department-Wise Highest Salary

SELECT Department,
       MAX(Salary) AS HighestSalary
FROM Employees
GROUP BY Department;
Output4 rows returned
DepartmentHighestSalary
Finance55000.00
HR35000.00
IT70000.00
Sales40000.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;
Output7 rows returned
CityDepartmentEmpCountTotalSalary
BangaloreIT2125000.00
ChennaiFinance155000.00
ChennaiHR135000.00
DelhiSales270000.00
HyderabadFinance150000.00
HyderabadIT2115000.00
MumbaiHR128000.00
The Golden Rule of GROUP BY (Common Interview Trap): Every non-aggregated column listed in your 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.
Class Pop Quiz #3

Why does SELECT City, EmployeeName, AVG(Salary) FROM Employees GROUP BY City; throw an error in SQL Server?

Answer: Because 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;
Output1 row returned
DepartmentTotalEmployees
IT4

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;
Output2 rows returned
DepartmentAverageSalary
Finance52500.000000
IT60000.000000

3. Cities Having More Than One Employee

SELECT City,
       COUNT(*) AS TotalEmployees
FROM Employees
GROUP BY City
HAVING COUNT(*) > 1;
Output4 rows returned
CityTotalEmployees
Bangalore2
Chennai2
Delhi2
Hyderabad3

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;
Output2 rows returned
DepartmentSeniorCountSeniorAvgSalary
IT365000.000000
Finance252500.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:

STEP 1
FROM

Loads the source table (Employees).

STEP 2
WHERE

Filters individual rows before grouping.

STEP 3
GROUP BY

Groups remaining rows into buckets.

STEP 4
HAVING

Filters summary groups using aggregates.

STEP 5
SELECT

Computes final expressions & column aliases.

STEP 6
ORDER BY / TOP

Sorts final rows and limits output count.

[Pro Tip — Alias Trap in SQL Server]: Because 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!
Class Pop Quiz #4

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
Class Pop Quiz #5

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.

SELECT COUNT(*) AS TotalEmployees FROM Employees; Output: TotalEmployees = 10
SELECT SUM(Salary) AS TotalSalary FROM Employees; Output: TotalSalary = 478000.00
SELECT AVG(Salary) AS AverageSalary FROM Employees; Output: AverageSalary = 47800.000000
SELECT MAX(Salary) AS HighestSalary FROM Employees; Output: HighestSalary = 70000.00 (Sneha)
SELECT MIN(Salary) AS LowestSalary FROM Employees; Output: LowestSalary = 28000.00 (Ravi)
SELECT Department, COUNT(*) AS TotalEmployees FROM Employees GROUP BY Department; Output: Finance | 2 HR | 2 IT | 4 Sales | 2
SELECT City, COUNT(*) AS TotalEmployees FROM Employees GROUP BY City; Output: Bangalore | 2 Chennai | 2 Delhi | 2 Hyderabad | 3 Mumbai | 1
SELECT Department, AVG(Salary) AS AverageSalary FROM Employees GROUP BY Department; Output: Finance | 52500.000000 HR | 31500.000000 IT | 60000.000000 Sales | 35000.000000
SELECT Department, COUNT(*) AS TotalEmployees FROM Employees GROUP BY Department HAVING COUNT(*) > 1; Output (all 4 departments qualify): Finance | 2 HR | 2 IT | 4 Sales | 2
SELECT City, AVG(Salary) AS AverageSalary FROM Employees GROUP BY City HAVING AVG(Salary) > 40000; Output (Delhi = 35,000 and Mumbai = 28,000 are excluded): Bangalore | 62500.000000 Chennai | 45000.000000 Hyderabad | 55000.000000
Final Boss Challenge

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.

Solution Query: SELECT City, COUNT(*) AS TotalEmployees, AVG(Salary) AS AverageSalary FROM Employees WHERE City <> 'Mumbai' GROUP BY City HAVING COUNT(*) >= 2 AND AVG(Salary) > 40000 ORDER BY AverageSalary DESC; Exact Output (3 rows): 1. Bangalore | 2 | 62500.000000 2. Hyderabad | 3 | 55000.000000 3. Chennai | 2 | 45000.000000

Your Day 3 Pop Quiz Score

Answer the clickable quiz questions above to track your mastery.

0 / 8

Post a Comment

0 Comments