AnalystPath

Classify Category Nodes

SQLMediumMid level~15 min

Problem

A product catalog stores its category hierarchy as a parent-pointer table.

```
Category
+-----------+------+
| Column | Type |
+-----------+------+
| node_id | int |
| parent_id | int |
+-----------+------+
node_id is the primary key. parent_id points to this node's parent node_id, or is NULL for the top of the tree.
```

Classify every node into one role:

- **Top** - the node has no parent (`parent_id` is NULL).
- **Branch** - the node has a parent and is itself the parent of at least one other node.
- **Leaf** - the node has a parent and no children.

Return `node_id` and its `role`, in any order.

Tables

Example rows — the live problem includes the full dataset.

Category
node_idparent_id
1
21
31

Expected output

Your answer should return 5 rows with the columns node_id, role.

Starter code (SQL)

SELECT *
FROM Category;

Solve this SQL question free

Write SQL and run it instantly in your browser — even on your phone. No signup needed to try.

Solution & explanation

Create a free account to unlock the optimal solution, a step-by-step explanation, and the hidden test cases that grade your answer.

Sign up free to unlock

Related SQL questions