← All SQL interview questions
Colleague pairs in the same city, different teams
MediumJoins — Self JoinOracleRSystems
The people team is planning cross-team coffee meetups and wants to pair colleagues who work in the same city but belong to different departments.
From staff, return each pair once as staff_a, dept_a, staff_b, dept_b and city. A pair must not appear twice in mirrored order, and nobody may be paired with themselves. Order by city, then the two staff_id values.
Sample data
Table: staff
12 row(s) · showing first 8
| staff_idINT | staff_nameTEXT | cityTEXT | departmentTEXT |
|---|---|---|---|
| 1 | Aditi Rao | Bengaluru | Data |
| 2 | Bilal Khan | Bengaluru | Engineering |
| 3 | Charu Iyer | Bengaluru | Data |
| 4 | Dinesh Pai | Pune | Engineering |
| 5 | Esha Joshi | Pune | Sales |
| 6 | Faisal Ahmed | Hyderabad | Data |
| 7 | Gita Nambiar | Hyderabad | Sales |
| 8 | Hari Om | Delhi | Engineering |
staff
- staff_idINT
- staff_nameTEXT
- cityTEXT
- departmentTEXT
- Step 1: Join the table to itself with two aliases, `a` and `b`, so each row can be compared with every other row.
- Step 2: `a.city = b.city` keeps same-city pairs and `a.department <> b.department` keeps different departments.
- Step 3: `a.staff_id < b.staff_id` removes self-pairs and keeps only one of each mirrored pair (A,B) and (B,A).
SELECT a.staff_name AS staff_a,
a.department AS dept_a,
b.staff_name AS staff_b,
b.department AS dept_b,
a.city
FROM staff a
JOIN staff b
ON a.city = b.city
AND a.department <> b.department
AND a.staff_id < b.staff_id
ORDER BY a.city, a.staff_id, b.staff_id;More Joins — Self Join questions
Practising alone only goes so far — our live cohorts pair SQL depth with dashboards, agentic analytics projects and mock interviews.
Explore the program