SQL intermediate self-join employees database query

How to Find Employee Pairs in the Same Department?

Self Join on Employees is a SQL query that this sql query retrieves pairs of employees who belong to the same department by joining the employees table with itself.. Formula Genius generates and validates this formula automatically from a plain-English prompt.

Using a self JOIN allows you to compare rows within the same table, making it easy to find employees in the same department.

The Formula

Prompt

"Find all pairs of employees who are in the same department using a self JOIN on the employees table"

SQL
SELECT e1.name AS Employee1, e2.name AS Employee2 FROM employees e1 JOIN employees e2 ON e1.department_id = e2.department_id WHERE e1.id < e2.id;

This SQL query retrieves pairs of employees who belong to the same department by joining the employees table with itself.

Step-by-Step Breakdown

  1. Select two instances of the employees table, aliased as e1 and e2.
  2. Join the two instances on the department_id to find employees in the same department.
  3. Use a WHERE clause to ensure that each pair is unique (e1.id < e2.id).
  4. Return the names of both employees in the resulting pairs.

Edge Cases & Warnings

  • Employees with the same name in the same department will be included in the results.
  • Departments with only one employee will not produce any pairs.
  • If there are no employees in the table, the query will return an empty result set.
  • Employees in different departments will not be matched.

Examples

Prompt

"Employees: (1, 'Alice', 101), (2, 'Bob', 101), (3, 'Charlie', 102)"

SQL
Pairs: (Alice, Bob)
Prompt

"Employees: (1, 'David', 103), (2, 'Eve', 103), (3, 'Frank', 103)"

SQL
Pairs: (David, Eve), (David, Frank), (Eve, Frank)

Frequently Asked Questions

What is a self JOIN?

A self JOIN is a regular join but the table is joined with itself.

Can I use self JOIN for other purposes?

Yes, self JOIN can be used to compare rows within the same table for various conditions.

What if my table has no department_id?

The query will not return any results if the department_id is missing for employees.

Can't find what you need?

Describe any formula in plain English and Formula Genius will generate, explain, and validate it — instantly.