SQL Joins Interview Question: Self Join

This problem statement is a part of our SQL Interview Questions series. In this series we are committed to bring out a collection of real-world interview questions to help job seekers improve their coding skills and gain confidence.

To check all the interview questions available in this series, click here.

SQL Joins

SQL joins helps in combining records from two or more than two tables in the SQL database, based on the related column between them. The different types of Joins available in SQL are:

  1. Inner Join
  2. Left Outer Join/Left Join
  3. Right Outer Join/Right Join
  4. Full Outer Join/Full Join
  5. Self Join
  6. Cross Join

Self Join is used for joining a table with itself and hence forms a unary relation. It is mainly used to combine and compare the rows of the same table in the database.

Let’s take you through an example of using the self join in practice.

Problem Statement:

Find the Employee Id and Name of the managers who have minimum 7 employees directly reporting to them.

Table: Employee_Info

EmpIDEmpNameAgeSexJobTitleSalaryManagerID
1Allen Jack50FManager40001
2Joe Wang27MAnalyst2001
3Henry Ted26MSenior Analyst4001
4Sam Aston22MAnalyst2001
5Mike George21MAnalyst2601
6Molly Sam23FAnalyst28013
7Nicky Bell28FAnalyst28013
8John Ford21MSenior Analyst30013
9Monika William28FAnalyst20013
10Jennifer Dion29FAnalyst20013
11Richerd Gear52MManager50001
12Shandler Bond23MAccountant22011
13Katty Bing51FManager30001
14Jason Tom18MAccountant20011
15Michale John39FAccountant14011
16Celine Anston22FAccountant20011
17Mick Berry39MSenior Analyst44011
18Laila Mark21FAnalyst20011
19George Joe45MManager20001
20Sarrah Bicky26FSenior Analyst40019
21Suzan Lee29FAnalyst26019
22Mandy John26FAnalyst26019
23Britney Berry42FAnalyst24019
24Smith Morris25MAnalyst26019
25Jack Hopes24MAnalyst26019
26Charles Ben38MAnalyst26019
27Tom Fredy27MAnalyst2401
28Morgan Matt25MAnalyst2401
29Antoney Adams29MAnalyst2601
30Mark Joe23MAnalyst2401

Solution:

Solution for Microsoft SQL Server is shared below.

SELECT ManagerID, ManagerName
FROM (
      SELECT E1.EmpID, E1.EmpName, E2.EmpName AS ManagerName, E2.EmpID AS ManagerID
      FROM Employee_Info AS E1 INNER JOIN Employee_Info AS E2
      ON E1.ManagerID = E2.EmpID) AS Table1
GROUP BY ManagerID, ManagerName
HAVING COUNT(EmpID) >= 7

Explanation: Please check the below video

 

Leave a Reply

Your email address will not be published. Required fields are marked *