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.
NULL values).INNER JOINLEFT JOINFULL OUTER JOINWhy 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:
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
| ID | Name | City |
|---|---|---|
| 101 | Rahul | Hyderabad |
| 102 | Anjali | Chennai |
| 103 | Kiran | Bangalore |
| 104 | Priya | Delhi |
| 105 | Arjun | Mumbai |
Enrollments
| EnrID | StuID | CrsID |
|---|---|---|
| 1 | 101 | 1 |
| 2 | 102 | 2 |
| 3 | 103 | 3 |
| 4 | 104 | 2 |
| 5 | 105 | 4 |
Courses
| ID | Course | Fees |
|---|---|---|
| 1 | SQL Server | 12000 |
| 2 | Python | 15000 |
| 3 | Java | 14000 |
| 4 | AI & ML | 25000 |
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;
| StudentName | CourseName | Fees |
|---|---|---|
| Rahul | SQL Server | 12000.00 |
| Anjali | Python | 15000.00 |
| Kiran | Java | 14000.00 |
| Priya | Python | 15000.00 |
| Arjun | AI & ML | 25000.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';
| StudentName | CourseName |
|---|---|
| Rahul | SQL 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;
| StudentName | CourseName | Fees |
|---|---|---|
| Arjun | AI & ML | 25000.00 |
| Anjali | Python | 15000.00 |
| Priya | Python | 15000.00 |
| Kiran | Java | 14000.00 |
| Rahul | SQL Server | 12000.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;
| StudentName | CourseName | InstructorName | Fees |
|---|---|---|---|
| Rahul | SQL Server | Suresh | 12000.00 |
| Anjali | Python | Meena | 15000.00 |
| Kiran | Java | Ramesh | 14000.00 |
| Priya | Python | Meena | 15000.00 |
| Arjun | AI & ML | Kavitha | 25000.00 |
JOIN ... ON conditions (3 tables = 2 ON conditions; 4 tables = 3 ON conditions).
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;
| CourseName | TotalStudents |
|---|---|
| AI & ML | 1 |
| Java | 1 |
| Python | 2 |
| SQL Server | 1 |
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;
| CourseName | AverageFee | TotalRevenue |
|---|---|---|
| AI & ML | 25000.000000 | 25000.00 |
| Java | 14000.000000 | 14000.00 |
| Python | 15000.000000 | 30000.00 |
| SQL Server | 12000.000000 | 12000.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;
| CourseName | TotalStudents | TotalRevenue |
|---|---|---|
| Python | 2 | 30000.00 |
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.
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.
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;
| Employee | Manager |
|---|---|
| John | NULL |
| David | John |
| Robert | John |
| James | David |
| Mary | David |
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).
M.EmployeeName with ISNULL(M.EmployeeName, 'Top Boss (No Manager)') so executives see clean text instead of NULL!
Real Company Examples of Self Join
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.
Interview Questions & Homework
Top 5 Advanced Join Interview Questions
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.StudentID, and are strictly required in a Self Join to distinguish the two instances of the same table.FROM and JOIN clauses as long as each reference is given a unique alias (for example, Employees E and Employees M).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:
Write SQL queries to complete all 8 tasks:
- Join
EmployeesandDepartments. - Join
Employees,Departments, andProjects(viaEmployeeProjects). - Display employee name, department, and project.
- Count employees in each department.
- Display projects assigned to each employee.
- Find employees who do not have any project (
LEFT JOIN+IS NULL). - Display departments with more than one employee (
GROUP BY+HAVING). - Create a Self Join to display Employee and Manager.
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!
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:
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.
0 Comments