When we want to select out all the record from two table, no matter it's present at second table or not, we will have to use SQL OUTER JOIN command.spa
There are 3 type of OUTER JOIN, which is:
LEFT OUTER JOIN
RIGHT OUTER JOIN
FULL OUTER JOINci
SQL OUTER JOIN syntax:it
SELECT *
FROM [TABLE 1] OUTER JOIN [TABLE 2]
ON [TABLE 1].[COLUMN NAME 1] = [TABLE 2].[COLUMN NAME 2]io
EXAMPLE :table
Let's say we got 2 tables containt data like Below: class
Table 1: GameScoresselect
PlayerName | DepartmentId | Scores |
Jason | 1 | 3000 |
Irene | 1 | 1500 |
Jane | 2 | 1000 |
David | 2 | 2500 |
Paul | 3 | 2000 |
James | 4 | 2000 |
Table 2: Departmentscommand
DepartmentId | DepartmentName |
1 | IT |
2 | Marketing |
3 | HR |
5 | QA |
LEFT OUTER JOIN will return all records from the first table,
SQL statement and Result for LEFT OUTER JOIN is :tab
SELECT * FROM GameScores2
LEFT OUTER JOIN Departments
ON GameScores2.DepartmentId = Departments.DepartmentId di
Result:
PlayerName | DepartmentId | Scores | DepartmentId | DepartmentName |
Jason | 1 | 3000 | 1 | IT |
Irene | 1 | 3000 | 1 | IT |
Jane | 2 | 3000 | 2 | Marketing |
David | 2 | 3000 | 2 | Marketing |
Paul | 3 | 3000 | 3 | HR |
James | 4 | 2000 | NULL | NULL |
RIGHT OUTER JOIN will return all records from the second table,
SQL statement and Result for RIGHT OUTER JOIN is :
SELECT * FROM GameScores2
RIGHT OUTER JOIN Departments
ON GameScores2.DepartmentId = Departments.DepartmentId
Result:
PlayerName | DepartmentId | Scores | DepartmentId | DepartmentName |
Jason | 1 | 3000 | 1 | IT |
Irene | 1 | 3000 | 1 | IT |
Jane | 2 | 3000 | 2 | Marketing |
David | 2 | 3000 | 2 | Marketing |
Paul | 3 | 3000 | 3 | HR |
NULL | NULL | NULL | 5 | QA |
FULL OUTER JOIN will return all records from all tables,
SQL statement and Result for FULL OUTER JOIN is :
SELECT * FROM GameScores2
FULL OUTER JOIN Departments
ON GameScores2.DepartmentId = Departments.DepartmentId
Result:
PlayerName | DepartmentId | Scores | DepartmentId | DepartmentName |
Jason | 1 | 3000 | 1 | IT |
Irene | 1 | 3000 | 1 | IT |
Jane | 2 | 3000 | 2 | Marketing |
David | 2 | 3000 | 2 | Marketing |
Paul | 3 | 3000 | 3 | HR |
James | 4 | 2000 | NULL | NULL |
NULL | NULL | NULL | 5 | QA |