Joins · Problem 48 of 118

Subcategories and Their Parents

EasyJoinsShop data

Return the subcategory name as subcategory and its parent's name as parent for every category that has a parent. Sort by parent, then subcategory.

Hint 1

categories.parent_id points to another row of the same table.

Reference solution

SELECT c.name AS subcategory, p.name AS parent
FROM categories AS c
JOIN categories AS p ON p.category_id = c.parent_id
ORDER BY p.name, c.name;

Same idea as the managers: parent_id holds the id of another row of the same table. Here an inner join is right, because we only want categories that have a parent; the top-level categories (with parent_id = NULL) are excluded by the join itself.