DataBolt

SQL LEARNING PLATFORM

14

CHAPTER 14

SELF JOINs

Joining a table to itself — useful for hierarchical relationships.

6

Learning Blocks

SQL

Interactive Queries

In This Chapter

Concepts you'll master

1

SELF JOIN is used to join a table with itself

2

Useful for hierarchical data (like employees and managers)

3

We use aliases to differentiate the same table

4

Each alias acts like a separate table

5

Common in real-world scenarios like org charts and reporting structure

🌟 Think of it this way: Imagine an employees table where each employee has a manager_id. To find who manages whom, we join the employees table with itself — one side is the employee, the other is the manager.

16.1 - SELF JOIN (Employee & Manager)

Shows each employee along with their manager name.

SQL QUERY
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m
ON e.manager_id = m.emp_id;

16.2 - SELF JOIN

A table joined to itself. Our employees table has manager_id referencing emp_id in the same table:

SQL QUERY
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.emp_id
ORDER BY e.name;

Engineering Insight: INNER JOIN vs LEFT JOIN is a decision, not a preference. Ask yourself: 'Is it valid for a row to have no match?' If yes, use LEFT JOIN. If a row must have a corresponding entry in the other table (by business rules), use INNER JOIN — it will surface data integrity issues.

Exercise

Practice your SQL skills

SQL EDITOR
Press semicolon (;) to auto-run query

Tasks

Complete all SQL challenges

1

Get employee names with their managers

Current Task
2

Find employees who do not have a manager

3

Find employees managed by Vikram

4

Sort employees by manager name

5

Count employees under each manager

6

Total salary under each manager

7

Employees with salary > 70000 and their managers

8

Employees from IT department with their managers

9

Employees whose managers are from Sales department

10

Employees hired after 2021 with their managers

Need help solving this task?