BIT202 · 0 · 5 marks
Define Outer Join in SQL. Given following relations, show the results of left and right outer joins. **Employee:** | Eid | Ename | Address | Dno | |---|---|---|---| | 1 | Ram | KTM | 111 | | 2 | Rita | PKR | 222 | | 3 | Hari | KTM | 333 | **Department:** | Dno | Dname | |---|---| | 111 | HRM | | 222
Define Outer Join in SQL. Given following relations, show the results of left and right outer joins.
Employee:
| Eid | Ename | Address | Dno |
|---|---|---|---|
| 1 | Ram | KTM | 111 |
| 2 | Rita | PKR | 222 |
| 3 | Hari | KTM | 333 |
Department:
| Dno | Dname |
|---|---|
| 111 | HRM |
| 222 | Admin |
| 444 | Account |
[5]
Database Management SystemChapter 6: SQL and Query ProcessingOuter joinsNumerical: outer join results
Outer Join in SQL
Given
Employee (E):
| Eid | Ename | Address | Dno |
|---|---|---|---|
| 1 | Ram | KTM | 111 |
| 2 | Rita | PKR | 222 |
| 3 | Hari | KTM | 333 |
Department (D):
| Dno | Dname |
|---|---|
| 111 | HRM |
| 222 | Admin |
| 444 | Account |
Join condition: E.Dno = D.Dno
Solution
Definition
An Outer Join returns all rows from one or both tables even when there is no matching row in the other table. Unmatched attributes are filled with NULL. Types:
- Left Outer Join - all rows of the left table plus matching rows of the right table.
- Right Outer Join - all rows of the right table plus matching rows of the left table.
- Full Outer Join - all rows from both tables.
Matching analysis
- E.Dno = 111 matches D.Dno = 111 (HRM)
- E.Dno = 222 matches D.Dno = 222 (Admin)
- E.Dno = 333 has no match in D
- D.Dno = 444 (Account) has no match in E
Left Outer Join
SELECT * FROM Employee E LEFT OUTER JOIN Department D ON E.Dno = D.Dno;
All Employee rows kept; Hari (333) has no department, so NULLs.
| Eid | Ename | Address | E.Dno | D.Dno | Dname |
|---|---|---|---|---|---|
| 1 | Ram | KTM | 111 | 111 | HRM |
| 2 | Rita | PKR | 222 | 222 | Admin |
| 3 | Hari | KTM | 333 | NULL | NULL |
Right Outer Join
SELECT * FROM Employee E RIGHT OUTER JOIN Department D ON E.Dno = D.Dno;
All Department rows kept; Account (444) has no employee, so NULLs.
| Eid | Ename | Address | E.Dno | D.Dno | Dname |
|---|---|---|---|---|---|
| 1 | Ram | KTM | 111 | 111 | HRM |
| 2 | Rita | PKR | 222 | 222 | Admin |
| NULL | NULL | NULL | NULL | 444 | Account |
Summary
| Join Type | Rows Retained | Extra NULL Row |
|---|---|---|
| Left Outer Join | All Employee rows | Hari (Dno 333) |
| Right Outer Join | All Department rows | Account (Dno 444) |
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.