Wednesday, December 18, 2024

SQL Self Join

 A Self Join in SQL is a join where a table is joined with itself. This can be useful when you want to compare rows within the same table or find relationships between rows that share the same structure. The table is aliased to differentiate the two instances of it in the join.

Here’s the basic syntax for a self join:

SELECT a.column1, a.column2, b.column1, b.column2
FROM table_name a, table_name b
WHERE a.some_column = b.some_column;

Example:

Consider a table employees with the following structure:

employee_id employee_name manager_id
1 Alice 3
2 Bob 3
3 Carol NULL
4 David 2

To find each employee and their manager's name, you can use a self join. Here’s the query:

SELECT e1.employee_name AS Employee, e2.employee_name AS Manager
FROM employees e1
LEFT JOIN employees e2 ON e1.manager_id = e2.employee_id;

Explanation:

  • e1 represents the first instance of the employees table, which is the employee.
  • e2 represents the second instance of the employees table, which is the manager.
  • The LEFT JOIN ensures that employees without managers (like Carol) are also included in the result, showing NULL for the manager.

Result:

Employee Manager
Alice Carol
Bob Carol
Carol NULL
David Bob

This is how a self join can be used to retrieve data from a single table by comparing rows within it.

No comments:

Post a Comment