Brightlane's product team is reviewing the category hierarchy and needs each subcategory paired with its parent category.
Write a query to return the subcategory name and parent category name for every subcategory that belongs to another category.
Assumptions:
- The
categoriestable contains every defined category in the catalogue. - The
parent_idcolumn links each subcategory to its parent — also a row incategories. - Top-level categories have
parent_idset toNULLand will not appear in the result.
Output:
- One row per subcategory, with columns
subcategory_nameandparent_category_name.
Schema · ecommerce 5 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
SELECT
c.name AS subcategory_name,
p.name AS parent_category_name
FROM
categories c
JOIN categories p ON c.parent_id = p.id The shape
The subcategory name and its parent name both live in categories, so the query joins the table to itself: one alias plays the subcategory role, the other plays the parent role, and c.parent_id = p.id links them.
Clause by clause
SELECT c.name AS subcategory_name, p.name AS parent_category_namepullsnamefrom both aliased instances.c.nameis the child category (Phones, Men's, Furniture);p.nameis the parent it rolls up to (Electronics, Clothing, Home & Garden).FROM categories creads the table in the subcategory role.JOIN categories p ON c.parent_id = p.idreads the same table again in the parent role and links each row'sparent_idto the matching row'sid. The top-level categories (Electronics, Clothing, Home & Garden) haveparent_id = NULL, so they never match anything inpand drop out of the result, which is what the prompt asks for.
The trap
The direction of the join condition matters. c.parent_id = p.id matches each child to its parent. Flipping it to c.id = p.parent_id reverses the roles: now p is the child and c is the parent, and the SELECT list returns parent names labeled as subcategory_name. Pick the alias that plays each role first, then write the condition in that direction.
You practiced a self-join on a parent-child column. The same shape that pairs employees with managers pairs subcategories with parent categories — the structure is identical, only the domain changes.