Kickstart 2020 with new opportunities! - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
3. Filtering self joined tables
Dictionary database
Summary

Instruction

Great! When self-joining tables, we can still filter the results with the WHERE clause, just as we can when JOINing two different tables.

Suppose that we want to show each employee's name along with the name of their supervisor for only those employees who have less than five years of experience:

SELECT
e.name AS employee_name,
s.name AS supervisor_name
FROM employee AS e
JOIN employee AS s
ON e.supervisor_id = s.id
WHERE e.experience < 5


Note that we always have to specify the table name (an alias) before a given column when self-joining. Otherwise, the column name would be ambiguous, as there would be two columns with the same name: one from the employee table, and one from the supervisor table.

Exercise

Show only worker's name, and specialization. Alias column with the name as apprentice. Consider only those workers whose supervisors have more than 14 years of experience.

Stuck? Here's a hint!

Type:

SELECT
apprentice.name apprentice,
apprentice.specialization
FROM workshop_workers apprentice
JOIN workshop_workers master
ON apprentice.master_id = master.id
WHERE master.experience > 14