You are on page 1of 4

DATABASE SYSTEMS-1

COMSATS University Islamabad, Wah Campus


Assignment # 04
Department of Computer Science

Class/Program: BS(SE)-4B Date: 23rd December, 2022


Subject: Database System Instructor: Dr. Saleha Masood
Maximum
Section: BSE-4B Marks: 10
Registration
Student Name: Waqar Tahir #: SP21-BSE-075

Question
Explain self join with the help of scenarios and examples.
Give the codes or queries as well.

Explanation:
Self join links a table to itself. this is usually done by joining a table to itself just
once within a sql query while most joins link two or more tables with each other to
present their data together.

The self join, as its name implies, joins a table to itself. To use a self join, the table
must contain a column that acts as the primary key and a different column that
stores values that can be matched up with the values in that column. The values of
both columns do not have to be the same for any given row, and the value in
second column may even be null.

December 23, 2022


1
DATABASE SYSTEMS-1

Considering the table Employees:

Manager
Id FullName Salary
Id

1 John Smith 10000 3

Jane
2 12000 3
Anderson

3 Tom Lanon 15000 4

4 Anne Connor 20000

5 Jeremy York 9000 1

This type of table structure is very common in hierarchies. Now, to show the name
of the manager for each employee in the same row, we can run the following
query:

Query:
SELECT employee.Id, employee.FullName, employee.ManagerId,
manager.FullName as ManagerName FROM Employees employee JOIN Employees
manager ON employee.ManagerId = manager.Id

December 23, 2022


2
DATABASE SYSTEMS-1

After the query is executed, we have the following result

Manager Manager
Id Full Name
Id Name

1 John Smith 3 Tom Lanon

Jane
2 3 Tom Lanon
Anderson

3 Tom Lanon 4 Anne Connor

Jeremy
5 1 John Smith
York

December 23, 2022


3
DATABASE SYSTEMS-1

References:
1) What Is a Self Join in SQL? An Explanation With Seven Examples |
LearnSQL.com
2) Lec-38: Self Join operation with Example | Database Management System -
YouTube

December 23, 2022


4

You might also like