Categories: SQL Training
Tags:

Here’s an example of two simple tables you can use to learn LEFT JOIN and RIGHT JOIN concepts in SQL:


Table 1: Students

StudentIDNameClass
1Alice10A
2Bob10B
3Charlie10A
4Diana10C

Table 2: Grades

StudentIDGrade
1A
2B
5A

Explanation of Joins

1. LEFT JOIN

  • A LEFT JOIN retrieves all records from the left table (Students) and the matching records from the right table (Grades).
  • If no match exists, the result will contain NULL values for the columns from the right table.
SELECT Students.StudentID, Students.Name, Students.Class, Grades.Grade
FROM Students
LEFT JOIN Grades
ON Students.StudentID = Grades.StudentID;

Result:

StudentIDNameClassGrade
1Alice10AA
2Bob10BB
3Charlie10ANULL
4Diana10CNULL

2. RIGHT JOIN

  • A RIGHT JOIN retrieves all records from the right table (Grades) and the matching records from the left table (Students).
  • If no match exists, the result will contain NULL values for the columns from the left table.
SELECT Students.StudentID, Students.Name, Students.Class, Grades.Grade
FROM Students
RIGHT JOIN Grades
ON Students.StudentID = Grades.StudentID;

Result:

StudentIDNameClassGrade
1Alice10AA
2Bob10BB
5NULLNULLA

These tables and queries provide a clear way to understand LEFT JOIN and RIGHT JOIN in SQL.

Here’s the SQL code for creating the Students and Grades tables and inserting the sample data:


Create Students Table

CREATE TABLE Students (
    StudentID INT PRIMARY KEY,
    Name VARCHAR(50),
    Class VARCHAR(10)
);

Insert Data into Students

INSERT INTO Students (StudentID, Name, Class)
VALUES 
(1, 'Alice', '10A'),
(2, 'Bob', '10B'),
(3, 'Charlie', '10A'),
(4, 'Diana', '10C');

Create Grades Table

CREATE TABLE Grades (
    StudentID INT PRIMARY KEY,
    Grade CHAR(1)
);

Insert Data into Grades

INSERT INTO Grades (StudentID, Grade)
VALUES 
(1, 'A'),
(2, 'B'),
(5, 'A');

Test the Data

You can now run the LEFT JOIN and RIGHT JOIN queries to verify the results:

LEFT JOIN Query

SELECT Students.StudentID, Students.Name, Students.Class, Grades.Grade
FROM Students
LEFT JOIN Grades
ON Students.StudentID = Grades.StudentID;

RIGHT JOIN Query

SELECT Students.StudentID, Students.Name, Students.Class, Grades.Grade
FROM Students
RIGHT JOIN Grades
ON Students.StudentID = Grades.StudentID;

This will help you see the relationships and missing data between the two tables. Let me know if you need help executing this or understanding the results!