← Back to SQL, page 18

sql-0348 · Hard senior

How would you model product categories that can nest to any depth?

The simplest model is an adjacency list (parent_id on each category), queried with recursive CTEs. A materialized path ('1/4/9') makes subtree queries a prefix match, and a closure table stores every ancestor-descendant pair for fast queries at the cost of more writes. Choose based on how often the tree changes and which queries dominate.

Full answer

Options:

  • Adjacency list: categories(id, parent_id REFERENCES categories). Moves are a single update; subtree and path queries need WITH RECURSIVE. Works well for small and medium trees.
  • Materialized path: store path = '1/4/9/'. Subtree is WHERE path LIKE '1/4/%', which an index can serve. Moving a subtree rewrites the path of every descendant. PostgreSQL's ltree extension provides this with operators.
  • Closure table: category_paths(ancestor, descendant, depth). Any subtree or ancestor query is one join; inserts add a row per ancestor, and moves rewrite many rows.
  • Nested sets: left and right numbers; fast reads but painful writes, now rarely chosen.

For an online shop, an adjacency list plus a cached path or breadcrumb column is usually enough. Guard against cycles: a CHECK cannot do it, so validate moves in the application or a trigger.

Key points

  • Adjacency list with recursive CTEs is simplest
  • Materialized paths make subtree queries prefix matches
  • Closure tables trade writes for fast reads
  • Prevent cycles on moves

Common mistakes

  • Fixed columns for level1, level2, level3
  • Ignoring the cost of moving subtrees

Follow-ups

  • How would you count products in a category and all its children?
  • How would you detect a cycle?

Tips

  • Compare read and write costs