Return every pair of employees in the same department: namea, nameb, departmentid, each pair once, no self-pairs.…
SQLLevel: IntermediateJoins and self-joins
Return every pair of employees in the same department: name_a, name_b, department_id, each pair once, no self-pairs.
Table definitions (from the source exercise):
CREATE TABLE employees(emp_id INTEGER PRIMARY KEY, name TEXT, department_id INTEGER, manager_id INTEGER, salary INTEGER, hire_date TEXT, job_title TEXT, gender TEXT);
Hints
- Define one output row and the source-table keys.
- Check duplicates, NULLs and the order of filtering and aggregation.
Answer
Approach: Self-join on department with a.emp_id < b.emp_id.
SELECT a.name AS name_a, b.name AS name_b, a.department_id
FROM employees a
JOIN employees b ON b.department_id = a.department_id
AND a.emp_id < b.emp_id;
The source uses SQLite with a MySQL compatibility layer. Date and string functions are dialect dependent; the query is preserved as published.
Source and licence: SQL Practice Lab — Ebrahim Sharifi · MIT