Brightlane's content team is reviewing the Clothing section and needs a list of all subcategories within it.
Write a query to return the subcategory name and parent category name for every subcategory whose parent is 'Clothing'.
Assumptions:
- The
categoriestable contains every defined category in the catalogue. - The condition
parent.name = 'Clothing'applies to the parent role of the self-pairing, not the subcategory role.
Output:
- One row per subcategory of Clothing, 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
WHERE
p.name = 'Clothing' The shape
The filter applies to the parent role, not the subcategory role, so the WHERE predicate names the parent alias: p.name = 'Clothing'. Each row in the result is a child of the Clothing category, and which alias the filter sits on is what makes that true.
Clause by clause
SELECT c.name AS subcategory_name, p.name AS parent_category_namereturns the child name and the parent name from the two aliased instances ofcategories.p.nameis'Clothing'on every row because of the filter below;c.namevaries across Men's, Women's, and Kids'.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 to its parent.WHERE p.name = 'Clothing'restricts the parent role to the row named'Clothing'. The subcategory role is unfiltered, so every child of Clothing is returned.
Why this and not WHERE c.name = 'Clothing'
The alias on the filter decides which role is being constrained. p.name = 'Clothing' returns the three children of Clothing. c.name = 'Clothing' would return one row — Clothing itself paired with its own parent (which is NULL, so actually zero rows in this schema). Same column, same value, different alias, opposite question. The prompt asks for subcategories of Clothing, so the filter names the parent.
The trap
When the same column exists on both aliases (c.name and p.name are both valid here), writing the filter without thinking about role assignment is the silent failure mode. The query parses, runs, and returns a result that looks reasonable until someone notices the row count is wrong. Decide which role the prompt is constraining first, then write the filter on that alias.
You practiced filtering on the parent side of a self-join. The recurring shape: per-alias filters are independent — choosing the right alias for each filter is what scopes the result correctly.