How do I compare records within the same table using a self-join?
Quick answer
Join the table to itself, giving each occurrence a different alias. Match the employee’s manager_id to the manager row’s employee_id. For example, employees AS e JOIN employees AS m ON e.manager_id = m.employee_id pairs the two rows. Select employee details from e and manager details from m, labeling the output columns so their roles are clear. [S1]
The question, the details, the next step.
A practical checklist
Identify the employee ID column and the column that stores the manager’s ID.
Give the two appearances of the table clear, different aliases, such as
eandm.Match
e.manager_idtom.employee_idin theONcondition.Select and label employee and manager fields separately to distinguish their roles.
Check the result you want and consult your database’s documentation if you need a different join type.
If results look unexpected, verify the ID columns and the rows being paired.
A few more useful answers
Why do the two table aliases need different names?
They distinguish the two roles played by the same table: the employee row and the manager row. Use the relevant alias before each column name, such as e.name or m.name. [S1]
Does this example include employees who have no matching manager row?
The example uses JOIN to show matched employee-manager pairs. For a different result, such as retaining employees without a match, check the documentation for your database and the join type you need.
Does this example tell me what my database columns are called?
No. employee_id, name, and manager_id are illustrative placeholders. Check your table definition and substitute its actual column names.
Sources
References used for this guide.
- [S1] SQLite SELECT: joining tables and ON constraints sqlite.org · Checked
