✏️ Explanatory Question

Find pairs of employees in the same department (no duplicate mirror pairs)

👁 5 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

143

Find pairs of employees in the same department (no duplicate mirror pairs)

Level: Coding Round — Tests the self-join "pairing" pattern and the classic trick to avoid duplicate and self-matched pairs.

The Puzzle: Given an employees table, list all pairs of employees who work in the same department. Each pair should appear only once (do not show both "A-B" and "B-A"), and an employee must not be paired with themselves.

Sample Data — employees

idnamedept_id
1Rumman10
2Krushna10
3Swetha10
4Ritesh20

Expected Output

employee_1employee_2dept_id
RummanKrushna10
RummanSwetha10
KrushnaSwetha10

Dept 10 has 3 people → 3 unique pairs. Ritesh is alone in dept 20 → no pair. Note "Krushna-Rumman" does NOT appear separately.

The essential trick — a.id < b.id: A plain self-join on dept_id would produce (1) self-pairs like "Rumman-Rumman" and (2) mirror duplicates like both "A-B" and "B-A". Adding a.id < b.id keeps only one ordering of each pair and eliminates self-matches in a single condition.

Solution — Self-Join with the id Ordering Trick

SELECT
    a.name AS employee_1,
    b.name AS employee_2,
    a.dept_id
FROM employees a
JOIN employees b
    ON a.dept_id = b.dept_id   -- same department
   AND a.id < b.id             -- avoids self-pairs AND mirror duplicates
ORDER BY a.dept_id, a.name, b.name;

Why Each Condition Matters

Join ConditionResult
a.dept_id = b.dept_id onlyIncludes self-pairs + both A-B and B-A
Add a.id != b.idRemoves self-pairs, but still has mirrors
Add a.id < b.idClean: no self-pairs, no mirrors

The pair-count math: A department with n employees produces n × (n-1) / 2 unique pairs. Dept 10 has 3 people → 3 × 2 / 2 = 3 pairs, matching our output. This is the "n choose 2" combination formula — handy to mention.

Bonus — Count Pairs per Department

SELECT a.dept_id, COUNT(*) AS pair_count
FROM employees a
JOIN employees b ON a.dept_id = b.dept_id AND a.id < b.id
GROUP BY a.dept_id;
-- Dept 10 -> 3 pairs, Dept 20 -> 0 (no row, single employee)

Interviewer follow-up: "Why use a.id < b.id instead of a.name < b.name?" → Use the id (or any unique key) because names can be duplicated — two employees named "Rumman" would break a name-based comparison (they would be wrongly filtered or paired). Ordering on a guaranteed-unique column like the primary key is always the safe choice for this de-duplication trick.