Interview Questions/SQL/Category Tree - Full Ancestor Path

Category Tree - Full Ancestor Path

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Description

You have a Categories table representing a tree (each category has an optional parent). Write a SQL query to produce the full path from the root to each node, formatted as 'Root > Child > Grandchild', and the depth of each node (root = 0). Return (id, name, full_path, depth) ordered by id. Table: Categories

Column NameTypeDescription
idINTPrimary key
nameVARCHARCategory name
parent_idINTNULL if this is a root category

Database Schema (Inferred)

Categories

Column NameExample Value
id1
nameElectronics
parent_idNULL

Example

Categories

idnameparent_id
1ElectronicsNULL
2Computers1
3Laptops2
4Gaming Laptops3
5Phones1
6Smartphones5

Output

idnamefull_pathdepth
1ElectronicsElectronics0
2ComputersElectronics > Computers1
3LaptopsElectronics > Computers > Laptops2
4Gaming LaptopsElectronics > Computers > Laptops > Gaming Laptops3
5PhonesElectronics > Phones1
6SmartphonesElectronics > Phones > Smartphones2

Explanation:

Anchor the CTE at root nodes (parent_id IS NULL). Recursively append each child's name to the parent's full_path and increment depth.

Approach hint

Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

SQL Editor
Loading...

Categories

idnameparent_id
1ElectronicsNULL
2Computers1
3Laptops2
4Gaming Laptops3
5Phones1
6Smartphones5

Output

idnamefull_pathdepth
1ElectronicsElectronics0
2ComputersElectronics > Computers1
3LaptopsElectronics > Computers > Laptops2
4Gaming LaptopsElectronics > Computers > Laptops > Gaming Laptops3
5PhonesElectronics > Phones1
6SmartphonesElectronics > Phones > Smartphones2