Show each child and its parent
Your task
Return each non-root category’s name as child_name and its parent’s name as parent_name. Sort by child ID.
Two aliases let one query refer to different rows in the same table.
Sample data
categories| id | name | parent_id |
|---|---|---|
| 1 | Music | NULL |
| 2 | Jazz | 1 |
| 3 | Indie | 1 |
| 4 | Bebop | 2 |
| 5 | Cool Jazz | 2 |
| 6 | Merch | NULL |
| 7 | Shirts | 6 |
Expected output
| child_name | parent_name |
|---|---|
| Jazz | Music |
| Indie | Music |
| Bebop | Jazz |
| Cool Jazz | Jazz |
| Shirts | Merch |
Show a hint
Join the child’s parent_id to the parent’s id.
Joins and set operations guide
Match rows by a key
A join combines columns horizontally. The condition links sales.album_id to albums.id. If an album has three sale records, a join can return its title three times.
SELECT s.id AS sale_id, a.title, s.quantity
FROM sales AS s
JOIN albums AS a ON a.id = s.album_id;Preserve rows without a match
A LEFT JOIN retains each album. The quantity condition belongs in ON because it defines which sales qualify as matches. Placing it in WHERE would also remove albums whose sale columns are NULL.
SELECT a.title, s.id AS large_sale_id
FROM albums AS a
LEFT JOIN sales AS s
ON s.album_id = a.id
AND s.quantity >= 3;Combine result sets vertically
UNION stacks compatible result sets and removes duplicate rows. UNION ALL keeps every row. INTERSECT keeps shared rows, and EXCEPT keeps rows unique to the first result. With set operations, both inputs must return the same number of columns.
SELECT title FROM albums WHERE genre = 'Jazz'
UNION
SELECT title FROM albums WHERE price < 20;Worked solution
SELECT c.name AS child_name, p.name AS parent_name FROM categories c JOIN categories p ON p.id=c.parent_id ORDER BY c.id;Press Control+Space for SQL suggestions. Use the arrow keys to select an option and Enter to insert it.
Results
Loading SQLite…
