Full answer
Options:
- Adjacency list:
categories(id, parent_id REFERENCES categories). Moves are a single update; subtree and path queries needWITH RECURSIVE. Works well for small and medium trees. - Materialized path: store
path = '1/4/9/'. Subtree isWHERE path LIKE '1/4/%', which an index can serve. Moving a subtree rewrites the path of every descendant. PostgreSQL'sltreeextension 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