SQL Server Day 5

Learn how tables connect using Primary Keys and Foreign Keys, and visually master INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN, CROSS JOIN, and Table Aliases with step-by-step outputs.

Quick Warm-Up Revision

Check your memory from the previous class before combining multiple tables. Tap any card to reveal the answer.

COUNT()
SUM()
AVG()
GROUP BY
HAVING

What is a JOIN? (Primary Key & Foreign Key)

In real applications, information is split across separate tables so data stays clean and never repeats unnecessarily. Suppose you have two small tables:

Students

StudentIDStudentName
1Rahul
2Anjali
3Kiran

Courses

StudentIDCourse
1SQL Server
2Python
3Java
[Question]: How can we display Rahul - SQL Server, Anjali - Python, and Kiran - Java together in one result?
[Answer]: Using a JOIN on the matching StudentID column!

Primary Key (PK)

Uniquely identifies every row in a table (no duplicates, no NULL). Example: Students.StudentID.

Foreign Key (FK)

Connects one table to another by pointing to the Primary Key of the parent table. Example: Courses.StudentID references Students.StudentID.

Practical Lab Setup: CollegeDB

Run this SQL script in SSMS to build Students (5 rows) and Courses (4 rows). Every Join diagram and output below uses these exact rows.

CREATE DATABASE CollegeDB;
GO

USE CollegeDB;
GO

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

INSERT INTO Students VALUES
(1, 'Rahul',  'Hyderabad'),
(2, 'Anjali', 'Chennai'),
(3, 'Kiran',  'Bangalore'),
(4, 'Priya',  'Delhi'),
(5, 'Arjun',  'Mumbai');

-- Table 2: Courses (Child Table linked via Foreign Key)
CREATE TABLE Courses
(
    CourseID INT PRIMARY KEY,
    StudentID INT,
    CourseName VARCHAR(100),
    Fees DECIMAL(10,2),
    FOREIGN KEY (StudentID) REFERENCES Students(StudentID)
);

INSERT INTO Courses VALUES
(101, 1, 'SQL Server',   12000),
(102, 2, 'Python',       15000),
(103, 3, 'Java',         14000),
(104, 5, 'Data Science', 25000);
Students.StudentID PK MATCHES ON Courses.StudentID FK

Look closely: StudentIDs 1, 2, 3, and 5 exist in both tables. StudentID 4 (Priya) has NOT enrolled in any course yet!

Table 1: Students (Left Table • 5 Rows)

StudentIDStudentNameCity
1RahulHyderabad
2AnjaliChennai
3KiranBangalore
4PriyaDelhi
5ArjunMumbai

Table 2: Courses (Right Table • 4 Rows)

CourseIDStudentIDCourseNameFees
1011SQL Server12000
1022Python15000
1033Java14000
1045Data Science25000
Class Pop Quiz #1

1. What is the purpose of FOREIGN KEY (StudentID) REFERENCES Students(StudentID) in the Courses table?

2. Looking at our two tables above, which student does NOT have a matching row in Courses?

1. INNER JOIN

Students Courses ONLY MATCHING ROWS
Most Used in Companies

Returns Only the Overlap

INNER JOIN returns rows only when there is a match in both tables. Any student without a course (like Priya) is skipped completely.

SELECT
    Students.StudentName,
    Courses.CourseName,
    Courses.Fees
FROM Students
INNER JOIN Courses
    ON Students.StudentID = Courses.StudentID;
Expected Output4 rows returned
StudentNameCourseNameFees
RahulSQL Server12000.00
AnjaliPython15000.00
KiranJava14000.00
ArjunData Science25000.00

Notice that Priya does not appear because she has no matching row in Courses.

2. LEFT JOIN (LEFT OUTER JOIN)

Students Courses ALL LEFT + MATCHED RIGHT
Keep Every Student

All Rows from Left Table

LEFT JOIN returns every row from the left table (Students) plus matching data from Courses. When no course exists, SQL Server fills the right columns with NULL.

SELECT
    Students.StudentName,
    Courses.CourseName
FROM Students
LEFT JOIN Courses
    ON Students.StudentID = Courses.StudentID;
Expected Output5 rows returned
StudentNameCourseName
RahulSQL Server
AnjaliPython
KiranJava
PriyaNULL
ArjunData Science

Now Priya appears with NULL for CourseName.

[Pro Pattern — Find Students Without Any Course]: Add WHERE Courses.CourseID IS NULL at the end of a LEFT JOIN to isolate only unmatched records (returns Priya). You will use this exact pattern in Homework #8!
Class Pop Quiz #2

1. How many rows does Students LEFT JOIN Courses return, and what appears in Priya's CourseName?

2. Which join should you use if you ONLY want students who have actually enrolled in a course?

3. RIGHT JOIN

Students Courses MATCHED LEFT + ALL RIGHT
RIGHT JOIN

Returns Every Course

RIGHT JOIN keeps every row from the right table (Courses) and brings in matching students. If a course has no assigned student (StudentID = NULL), StudentName shows NULL.

SELECT
    Students.StudentName,
    Courses.CourseName
FROM Students
RIGHT JOIN Courses
    ON Students.StudentID = Courses.StudentID;
Expected Output4 rows returned
StudentNameCourseName
RahulSQL Server
AnjaliPython
KiranJava
ArjunData Science

All 4 courses in our table currently belong to a valid student (1, 2, 3, 5). If you inserted (105, NULL, 'Power BI', 18000) into Courses, RIGHT JOIN would display NULL | Power BI.

4. FULL OUTER JOIN

Students Courses EVERYTHING FROM BOTH
FULL OUTER JOIN

All Students + All Courses

FULL OUTER JOIN combines LEFT JOIN and RIGHT JOIN. It returns every matched row, every unmatched student (with NULL course), and every unmatched course (with NULL student).

SELECT
    Students.StudentName,
    Courses.CourseName
FROM Students
FULL OUTER JOIN Courses
    ON Students.StudentID = Courses.StudentID;
Expected Output5 rows returned
StudentNameCourseName
RahulSQL Server
AnjaliPython
KiranJava
PriyaNULL
ArjunData Science

Nothing is dropped from either side: Priya is kept from Students, and any unassigned course would also be kept from Courses.

Class Pop Quiz #3

Suppose a new course (105, NULL, 'Power BI', 18000) is added to Courses with no student yet. Which Join will show both Priya (no course) and Power BI (no student) in the same result?

Answer: FULL OUTER JOIN! LEFT JOIN would hide Power BI, and RIGHT JOIN would hide Priya. Only FULL OUTER JOIN preserves unmatched rows from both tables (6 rows total).

5. CROSS JOIN & Table Aliases

Students 5 rows Courses 4 rows 5 x 4 = 20 COMBINATIONS
Cartesian Product

Every Student x Every Course

CROSS JOIN requires no ON condition. It multiplies every row of the first table by every row of the second table: 5 Students × 4 Courses = 20 Rows.

SELECT
    Students.StudentName,
    Courses.CourseName
FROM Students
CROSS JOIN Courses;
Sample Output20 rows total (5 x 4)
StudentNameCourseName
RahulSQL Server
RahulPython
RahulJava
RahulData Science
AnjaliSQL Server
... (15 more combinations)...

Real-world use: generating all combinations such as Shirt Sizes (S, M, L) × Colors (Red, Blue, Black).

Making Queries Clean with Table Aliases

Instead of repeating full table names like Students.StudentName and Courses.CourseName, give each table a short nickname (alias) such as S and C:

SELECT
    S.StudentName,
    C.CourseName
FROM Students S
INNER JOIN Courses C
    ON S.StudentID = C.StudentID;
[Pro Tip]: Aliases make multi-table queries much shorter and easier to read. Once you assign Students S, always use S.ColumnName everywhere in that query.

All 5 SQL Joins — Quick Summary Table

Join Type What It Returns Rows (Our Data)
INNER JOINOnly matching rows in both tables4 rows
LEFT JOINAll left rows + matched right rows (NULL if no match)5 rows
RIGHT JOINAll right rows + matched left rows (NULL if no match)4 rows
FULL OUTER JOINAll rows from both tables (NULL where unmatched)5 rows
CROSS JOINEvery possible combination (Left × Right)20 rows
Class Pop Quiz #4

1. If Table A has 6 rows and Table B has 5 rows, how many rows will A CROSS JOIN B return?

2. Which SQL Join does NOT take an ON condition?

Class Practice (10 Queries with Outputs)

Try writing each query on CollegeDB in SSMS using table aliases (S and C), then tap any card to verify your SQL and output.

SELECT S.StudentName, C.CourseName FROM Students S INNER JOIN Courses C ON S.StudentID = C.StudentID; Output (4 rows): Rahul - SQL Server, Anjali - Python, Kiran - Java, Arjun - Data Science
SELECT S.StudentName, C.Fees FROM Students S INNER JOIN Courses C ON S.StudentID = C.StudentID; Output (4 rows): Rahul (12000), Anjali (15000), Kiran (14000), Arjun (25000)
SELECT S.StudentName, C.CourseName FROM Students S LEFT JOIN Courses C ON S.StudentID = C.StudentID; Output (5 rows): Includes Priya with CourseName = NULL
SELECT S.StudentName, C.CourseName FROM Students S RIGHT JOIN Courses C ON S.StudentID = C.StudentID; Output (4 rows): SQL Server, Python, Java, Data Science
SELECT S.StudentName, C.CourseName FROM Students S FULL OUTER JOIN Courses C ON S.StudentID = C.StudentID; Output (5 rows): All 5 students (Priya shows NULL) and all 4 courses
SELECT S.StudentName, C.CourseName FROM Students S CROSS JOIN Courses C; Output: 20 rows (5 Students x 4 Courses)
SELECT S.StudentName, S.City, C.CourseName, C.Fees FROM Students S INNER JOIN Courses C ON S.StudentID = C.StudentID; Output (4 rows): Rahul (Hyderabad, SQL Server, 12000), Anjali (Chennai, Python, 15000), Kiran (Bangalore, Java, 14000), Arjun (Mumbai, Data Science, 25000)
SELECT S.StudentName, C.CourseName, C.Fees FROM Students S INNER JOIN Courses C ON S.StudentID = C.StudentID WHERE C.Fees > 14000; Output (2 rows): Anjali (Python, 15000.00) and Arjun (Data Science, 25000.00)
SELECT S.StudentName, S.City, C.CourseName FROM Students S INNER JOIN Courses C ON S.StudentID = C.StudentID WHERE S.City = 'Hyderabad'; Output (1 row): Rahul | Hyderabad | SQL Server
SELECT S.StudentName, C.CourseName FROM Students S LEFT JOIN Courses C ON S.StudentID = C.StudentID ORDER BY S.StudentName; Output (5 rows A-Z): Anjali, Arjun, Kiran, Priya (NULL), Rahul

Interview Questions & Homework

Top 5 SQL Joins Interview Questions

A column (or set of columns) that uniquely identifies each record in a table. It cannot contain duplicate or NULL values.
A column in one table that references the Primary Key of another table to create and enforce a relationship between the two tables.
INNER JOIN (followed closely by LEFT JOIN for reporting).
LEFT JOIN (returns all left rows plus matching right rows, filling unmatched columns with NULL).
CROSS JOIN (produces the Cartesian product: Left Rows × Right Rows).

Homework Assignment: Customers & Orders

Create two tables with a Primary Key → Foreign Key relationship:

Customers (Insert 5 Records)

CustomerID (PK), CustomerName, City

Orders (Insert 8 Records)

OrderID (PK), CustomerID (FK), Product, Amount

Write SQL queries for all 10 tasks:

  1. INNER JOIN
  2. LEFT JOIN
  3. RIGHT JOIN
  4. FULL OUTER JOIN
  5. CROSS JOIN
  6. Display Customer Name and Product.
  7. Display Customer Name and Amount.
  8. Display customers without orders.
  9. Display orders without matching customers (if any).
  10. Display customers from Hyderabad with their orders.
Final Boss Challenge

Using Students and Courses, write a query to display only the student name(s) and city who have NOT enrolled in any course yet (without hardcoding StudentID = 4).

Solution (LEFT JOIN + IS NULL Anti-Join Pattern): SELECT S.StudentName, S.City FROM Students S LEFT JOIN Courses C ON S.StudentID = C.StudentID WHERE C.CourseID IS NULL; Exact Output (1 row): Priya | Delhi

Coming Up Next: Class 6 — Advanced Joins & Subqueries

In the next session, we level up to real-world SQL development and technical interview favorites:

Self Join Self Join Examples UNION UNION ALL Subqueries Nested Queries EXISTS NOT EXISTS

Your Tutorial 5 Pop Quiz Score

Answer the clickable quiz questions above to track your mastery.

0 / 6

Post a Comment

0 Comments