Menu
Coddy logo textTech

Self join

Part of the Fundamentals section of Coddy's SQL journey — lesson 46 of 72.

Self-joins are different types of joins. As of now, we talked about multiple table joins, but self-joins are joined to the same table. A classic example would be a table of employees.

employee_idemployee_namemanager_id
1Minke2
2Temur3
3Tatjana4
4Marinela 

Every employee has a manager except the highest manager, and every manager is also an employee.

The problem: For each employee we want to know the manager's name.

SELECT e2.employee_id, e2.employee_name, e1.employee_name as manager_name
FROM employees as e1
JOIN employees as e2 ON e1.employee_id = e2.manager_id

We join between the same table except one time we call it e1 and the second time it is e2. The join is between the fields employee_id and manager_id.

The result:

employee_idemployee_namemanager_name
1MinkeTemur
2TemurTatjana
3TatjanaMarinela
challenge icon

Challenge

Medium

Available tables and columns:

  • <strong>friends</strong>: <strong>id</strong>, <strong>name</strong>, <strong>friend_id</strong>

Find pairs of friends who are mutual friends (mutual friendship exists when person A's friend_id points to person B AND person B's friend_id points to person A). Display both friends names in a single row. Name the columns friend1 and friend2.

Note: Include in the WHERE clause the criteria friend1.id < friend2.id so that it will not include duplicate pairs 

Try it yourself

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals