SQL Server Day 6

Learn how real companies connect three and four tables through bridge tables, combine Joins with WHERE, ORDER BY, and GROUP BY for reporting, and master Self Joins to query employee-manager hierarchies.

Quick Warm-Up Revision

Refresh your fundamentals from Tutorial 5 before chaining multiple tables together. Tap any question to verify your answer.

A Primary Key uniquely identifies every record in a table (no duplicates and no NULL values).
A Foreign Key creates a relationship between two tables by linking to the Primary Key of another table.
INNER JOIN
LEFT JOIN
FULL OUTER JOIN

Why Three Tables? & CollegeManagement Setup

Real companies never dump students, courses, and fees into one giant table. If 100 students take Python, storing the course name and fee 100 times causes duplicate data and update headaches. Instead, databases use a bridge table (also called a junction table) in the middle:

How a Bridge Table Connects Students & Courses
Students (S) PK StudentID StudentName City 1 : Many Enrollments (E) PK EnrollmentID FK StudentID FK CourseID Many : 1 Courses (C) PK CourseID CourseName Fees

Students connects to Enrollments via StudentID, and Enrollments connects to Courses via CourseID. One student can enroll in many courses, and one course can have many students.

Step-by-Step Database Setup Script

Copy and run this complete script in SSMS to create CollegeManagement and insert all records into Students, Courses, and Enrollments:

CREATE DATABASE CollegeManagement;
GO

USE CollegeManagement;
GO

-- Table 1: Students
CREATE TABLE Students
(
    StudentID INT PRIMARY KEY,
    StudentName VARCHAR(100),
    City VARCHAR(50)
);

INSERT INTO Students VALUES
(101, 'Rahul',  'Hyderabad'),
(102, 'Anjali', 'Chennai'),
(103, 'Kiran',  'Bangalore'),
(104, 'Priya',  'Delhi'),
(105, 'Arjun',  'Mumbai');

-- Table 2: Courses
CREATE TABLE Courses
(
    CourseID INT PRIMARY KEY,
    CourseName VARCHAR(100),
    Fees DECIMAL(10,2)
);

INSERT INTO Courses VALUES
(1, 'SQL Server', 12000),
(2, 'Python',     15000),
(3, 'Java',       14000),
(4, 'AI & ML',    25000);

-- Table 3: Enrollments (Bridge Table)
CREATE TABLE Enrollments
(
    EnrollmentID INT PRIMARY KEY,
    StudentID INT,
    CourseID INT,
    FOREIGN KEY (StudentID) REFERENCES Students(StudentID),
    FOREIGN KEY (CourseID)  REFERENCES Courses(CourseID)
);

INSERT INTO Enrollments VALUES
(1, 101, 1),
(2, 102, 2),
(3, 103, 3),
(4, 104, 2),
(5, 105, 4);

Students

IDNameCity
101RahulHyderabad
102AnjaliChennai
103KiranBangalore
104PriyaDelhi
105ArjunMumbai

Enrollments

EnrIDStuIDCrsID
11011
21022
31033
41042
51054

Courses

IDCourseFees
1SQL Server12000
2Python15000
3Java14000
4AI & ML25000
Class Pop Quiz #1

1. Why do real companies create a middle bridge table like Enrollments instead of putting everything into one table?

Joining Three & Four Tables (with WHERE & ORDER BY)

Think of multi-table joins like connecting train coaches: first join Students to Enrollments, and then join Enrollments to Courses.

1. Joining Three Tables

SELECT
    S.StudentName,
    C.CourseName,
    C.Fees
FROM Students S
INNER JOIN Enrollments E
    ON S.StudentID = E.StudentID
INNER JOIN Courses C
    ON E.CourseID = C.CourseID;
Output5 rows returned
StudentNameCourseNameFees
RahulSQL Server12000.00
AnjaliPython15000.00
KiranJava14000.00
PriyaPython15000.00
ArjunAI & ML25000.00

Notice how both Anjali (102) and Priya (104) share CourseID 2 (Python), yet Python's name and fee are stored only once in Courses.

2. JOIN + WHERE (Filtering Joined Rows)

Add a WHERE clause after all JOIN lines to filter by any column from any joined table (always prefix with the table alias):

-- Students from Hyderabad with their enrolled courses
SELECT
    S.StudentName,
    C.CourseName
FROM Students S
INNER JOIN Enrollments E
    ON S.StudentID = E.StudentID
INNER JOIN Courses C
    ON C.CourseID = E.CourseID
WHERE S.City = 'Hyderabad';
Output1 row returned
StudentNameCourseName
RahulSQL Server

3. JOIN + ORDER BY (Sorting Joined Rows)

-- Display enrollments sorted by highest fee first
SELECT
    S.StudentName,
    C.CourseName,
    C.Fees
FROM Students S
INNER JOIN Enrollments E
    ON S.StudentID = E.StudentID
INNER JOIN Courses C
    ON C.CourseID = E.CourseID
ORDER BY C.Fees DESC;
Output5 rows sorted by Fees DESC
StudentNameCourseNameFees
ArjunAI & ML25000.00
AnjaliPython15000.00
PriyaPython15000.00
KiranJava14000.00
RahulSQL Server12000.00

4. Scaling Up: Joining Four Tables

Once you understand 3 tables, joining 4 (or even 10) tables follows the exact same chain rule. Suppose we add a 4th table called Instructors that stores who teaches each course:

-- Optional 4th Table: Instructors
CREATE TABLE Instructors
(
    InstructorID INT PRIMARY KEY,
    InstructorName VARCHAR(100),
    CourseID INT,
    FOREIGN KEY (CourseID) REFERENCES Courses(CourseID)
);

INSERT INTO Instructors VALUES
(1, 'Suresh',  1),
(2, 'Meena',   2),
(3, 'Ramesh',  3),
(4, 'Kavitha', 4);

-- 4-Table Join: Students -> Enrollments -> Courses -> Instructors
SELECT
    S.StudentName,
    C.CourseName,
    I.InstructorName,
    C.Fees
FROM Students S
INNER JOIN Enrollments E ON S.StudentID = E.StudentID
INNER JOIN Courses C     ON E.CourseID = C.CourseID
INNER JOIN Instructors I ON C.CourseID = I.CourseID;
4-Table Join Output5 rows returned
StudentNameCourseNameInstructorNameFees
RahulSQL ServerSuresh12000.00
AnjaliPythonMeena15000.00
KiranJavaRamesh14000.00
PriyaPythonMeena15000.00
ArjunAI & MLKavitha25000.00
[Pro Tip — Joining N Tables]: To join N tables cleanly without a Cartesian explosion, you always need at least N - 1 JOIN ... ON conditions (3 tables = 2 ON conditions; 4 tables = 3 ON conditions).
Class Pop Quiz #2

1. How many JOIN ... ON clauses are needed to connect 4 tables in a chain?

2. When writing a 3-table query with filtering and sorting, where does the WHERE clause go?

JOIN with Aggregate Functions & GROUP BY

Combining JOIN with COUNT(), SUM(), AVG(), and GROUP BY is how business dashboards and management reports are built.

1. Count Students in Each Course

SELECT
    C.CourseName,
    COUNT(*) AS TotalStudents
FROM Courses C
INNER JOIN Enrollments E
    ON C.CourseID = E.CourseID
GROUP BY C.CourseName;
Output4 rows returned
CourseNameTotalStudents
AI & ML1
Java1
Python2
SQL Server1

2. Course-Wise Average Fee & Total Revenue

-- Average fee per course
SELECT
    C.CourseName,
    AVG(C.Fees) AS AverageFee,
    SUM(C.Fees) AS TotalRevenue
FROM Courses C
INNER JOIN Enrollments E
    ON C.CourseID = E.CourseID
GROUP BY C.CourseName;
Output4 rows returned
CourseNameAverageFeeTotalRevenue
AI & ML25000.00000025000.00
Java14000.00000014000.00
Python15000.00000030000.00
SQL Server12000.00000012000.00

Python has 2 enrolled students (Anjali and Priya), so its TotalRevenue is 15,000 + 15,000 = ₹30,000.00 while its AverageFee stays ₹15,000.

3. Real-World Report: JOIN + GROUP BY + HAVING

Find only the popular courses that have more than 1 enrolled student:

SELECT
    C.CourseName,
    COUNT(E.EnrollmentID) AS TotalStudents,
    SUM(C.Fees)           AS TotalRevenue
FROM Courses C
INNER JOIN Enrollments E
    ON C.CourseID = E.CourseID
GROUP BY C.CourseName
HAVING COUNT(E.EnrollmentID) > 1;
Output1 row returned
CourseNameTotalStudentsTotalRevenue
Python230000.00
Subtle Interview Trap (LEFT JOIN + COUNT): If a course has 0 enrollments and you use LEFT JOIN, writing COUNT(*) wrongly returns 1 (because it counts the NULL row!). Always write COUNT(E.EnrollmentID) with LEFT JOIN so empty courses accurately show 0.
Class Pop Quiz #3

1. You use Courses C LEFT JOIN Enrollments E to show every course, including courses with 0 students. Which count gives 0 for empty courses?

Self Join — Joining a Table with Itself

A Self Join is not a special SQL keyword—it simply means joining the same table to itself using two different aliases so SQL Server treats it like two separate copies.

Visualizing the Employee → Manager Hierarchy
1. John (Top Boss) ManagerID = NULL 2. David ManagerID = 1 (John) 3. Robert ManagerID = 1 (John) 4. James ManagerID = 2 (David) 5. Mary ManagerID = 2 (David)

ManagerID points back to EmployeeID inside the exact same table. To look up each manager's name, we match E.ManagerID = M.EmployeeID.

Create & Populate the Employees Table

CREATE TABLE Employees
(
    EmployeeID INT PRIMARY KEY,
    EmployeeName VARCHAR(100),
    ManagerID INT NULL
);

INSERT INTO Employees VALUES
(1, 'John',   NULL),
(2, 'David',  1),
(3, 'Robert', 1),
(4, 'James',  2),
(5, 'Mary',   2);

Self Join Query (Using LEFT JOIN)

We use the same Employees table twice: alias E acts as the Employee copy, and alias M acts as the Manager copy.

SELECT
    E.EmployeeName AS Employee,
    M.EmployeeName AS Manager
FROM Employees E
LEFT JOIN Employees M
    ON E.ManagerID = M.EmployeeID;
Output5 rows returned
EmployeeManager
JohnNULL
DavidJohn
RobertJohn
JamesDavid
MaryDavid

Using LEFT JOIN keeps John in the output with NULL as his Manager. If you used INNER JOIN instead, John would disappear (only 4 rows returned).

[Pro Tip — Replace NULL with Friendly Text]: In real dashboards, wrap M.EmployeeName with ISNULL(M.EmployeeName, 'Top Boss (No Manager)') so executives see clean text instead of NULL!

Real Company Examples of Self Join

Employees → Managers: Org charts and reporting lines.
Students → Mentors: Senior students mentoring juniors.
Products → Parent Products: Categories and sub-categories.
Folders → Parent Folders: Nested Google Drive / Windows directories.
Comments → Parent Comments: Replies nested under YouTube or blog comments.
Flights / Routes: Matching connecting legs in the same schedule table.
Class Pop Quiz #4

1. Why are table aliases (E and M) mandatory in a Self Join?

2. How many rows are returned if we change LEFT JOIN to INNER JOIN in our Self Join query?

Class Practice (10 Queries with Outputs)

Write all 10 queries in SSMS on CollegeManagement, then click any card to verify both the SQL command and expected output.

SELECT S.StudentName, C.CourseName FROM Students S INNER JOIN Enrollments E ON S.StudentID = E.StudentID INNER JOIN Courses C ON E.CourseID = C.CourseID; Output (5 rows): Rahul - SQL Server, Anjali - Python, Kiran - Java, Priya - Python, Arjun - AI & ML
SELECT S.StudentName, C.Fees FROM Students S INNER JOIN Enrollments E ON S.StudentID = E.StudentID INNER JOIN Courses C ON E.CourseID = C.CourseID; Output (5 rows): Rahul (12000), Anjali (15000), Kiran (14000), Priya (15000), Arjun (25000)
SELECT S.StudentName, S.City, C.CourseName FROM Students S INNER JOIN Enrollments E ON S.StudentID = E.StudentID INNER JOIN Courses C ON E.CourseID = C.CourseID WHERE S.City = 'Hyderabad'; Output (1 row): Rahul | Hyderabad | SQL Server
SELECT S.StudentName, C.CourseName, C.Fees FROM Students S INNER JOIN Enrollments E ON S.StudentID = E.StudentID INNER JOIN Courses C ON E.CourseID = C.CourseID ORDER BY C.Fees DESC; Output (highest to lowest): Arjun (25000), Anjali (15000), Priya (15000), Kiran (14000), Rahul (12000)
SELECT C.CourseName, COUNT(*) AS TotalStudents FROM Courses C INNER JOIN Enrollments E ON C.CourseID = E.CourseID GROUP BY C.CourseName; Output: AI & ML (1), Java (1), Python (2), SQL Server (1)
SELECT MAX(Fees) AS HighestFee FROM Courses; Output: HighestFee = 25000.00 (AI & ML)
SELECT MIN(Fees) AS LowestFee FROM Courses; Output: LowestFee = 12000.00 (SQL Server)
-- Average across the 4 courses in the catalog: SELECT AVG(Fees) AS AverageCourseFee FROM Courses; -- Or average across all 5 student enrollments: SELECT AVG(C.Fees) AS AverageEnrolledFee FROM Courses C INNER JOIN Enrollments E ON C.CourseID = E.CourseID; Catalog Average: 16500.000000 (66,000 / 4) Enrolled Average: 16200.000000 (81,000 / 5)
SELECT E.EmployeeName AS Employee, M.EmployeeName AS Manager FROM Employees E LEFT JOIN Employees M ON E.ManagerID = M.EmployeeID; Output (5 rows): John - NULL, David - John, Robert - John, James - David, Mary - David
SELECT EmployeeName FROM Employees WHERE ManagerID IS NULL; Output (1 row): John

Interview Questions & Homework

Top 5 Advanced Join Interview Questions

A Self Join is a regular join (INNER JOIN or LEFT JOIN) where a table is joined with itself using two different aliases, typically to query hierarchical or parent-child relationships like Employees and Managers.
Aliases make multi-table queries shorter and easier to read, prevent column-name ambiguity when two tables share columns like StudentID, and are strictly required in a Self Join to distinguish the two instances of the same table.
Yes. SQL Server lets you reference the same table multiple times in the FROM and JOIN clauses as long as each reference is given a unique alias (for example, Employees E and Employees M).
Bridge (junction) tables resolve many-to-many relationships without duplicating data. Instead of repeating student info inside Courses or course fees inside Students, Enrollments stores only the connecting Foreign Keys (StudentID and CourseID).
INNER JOIN is a join type that returns only matching rows (usually across two different tables). A Self Join is a join pattern where one table joins with itself—and it can be written using either INNER JOIN or LEFT JOIN depending on whether you want to keep top-level NULL rows.

Homework Assignment: 4-Table Company Schema

Create these four related tables and insert at least 5 records into each table:

1. Departments 2. Employees 3. Projects 4. EmployeeProjects (Bridge)

Write SQL queries to complete all 8 tasks:

  1. Join Employees and Departments.
  2. Join Employees, Departments, and Projects (via EmployeeProjects).
  3. Display employee name, department, and project.
  4. Count employees in each department.
  5. Display projects assigned to each employee.
  6. Find employees who do not have any project (LEFT JOIN + IS NULL).
  7. Display departments with more than one employee (GROUP BY + HAVING).
  8. Create a Self Join to display Employee and Manager.
Final Boss Challenge

Using our Employees table, combine a Self Join with GROUP BY to display each Manager's Name and the number of employees reporting directly to them!

Solution (Self Join + GROUP BY): SELECT M.EmployeeName AS ManagerName, COUNT(E.EmployeeID) AS TeamSize FROM Employees E INNER JOIN Employees M ON E.ManagerID = M.EmployeeID GROUP BY M.EmployeeName ORDER BY TeamSize DESC; Exact Output (2 rows): David | 2 (manages James, Mary) John | 2 (manages David, Robert)

Coming Up Next: Class 7 — Subqueries

You have now completed the Core SQL foundation (Classes 1–6). Starting in Class 7, we move into intermediate and advanced SQL Server features heavily tested in real-world projects and technical interviews:

Single Row Subqueries Multi Row Subqueries Correlated Subqueries EXISTS NOT EXISTS Interview Questions Company Examples

Classes 1–6 (Completed)

Core SQL Server practical foundation: setup, CRUD, filtering, aggregates, grouping, basic joins, multi-table joins, and self joins.

Classes 7–25 (Up Next)

Subqueries, CTEs, Window Functions, Views, Stored Procedures, Triggers, Indexes, and interview-grade SQL development.

Your Tutorial 6 Pop Quiz Score

Answer the clickable quiz questions above to track your score.

0 / 6

Post a Comment

0 Comments