SQL intermediate

How to Find Employee Pairs in the Same Department?

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

Formula Genius can generate a draft from a plain-English prompt. Supported formulas can be checked with sample cases; review the coverage on the result.

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 a formula in plain English. Formula Genius drafts and explains it, and can check supported formulas on sample cases.