Here’s an example of two simple tables you can use to learn LEFT JOIN and RIGHT JOIN concepts in SQL:
Table 1: Students
| StudentID | Name | Class |
|---|---|---|
| 1 | Alice | 10A |
| 2 | Bob | 10B |
| 3 | Charlie | 10A |
| 4 | Diana | 10C |
Table 2: Grades
| StudentID | Grade |
|---|---|
| 1 | A |
| 2 | B |
| 5 | A |
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
NULLvalues 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:
| StudentID | Name | Class | Grade |
|---|---|---|---|
| 1 | Alice | 10A | A |
| 2 | Bob | 10B | B |
| 3 | Charlie | 10A | NULL |
| 4 | Diana | 10C | NULL |
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
NULLvalues 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:
| StudentID | Name | Class | Grade |
|---|---|---|---|
| 1 | Alice | 10A | A |
| 2 | Bob | 10B | B |
| 5 | NULL | NULL | A |
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!
