Video in progress
To store a category tree, which do you choose: an adjacency list, a materialized path (`ltree`), or a closure table?
adjacency list / ltree path / closure table — Parent: parent_id / path = 'elektronika.telefon.smartfon' / (ancestor, descendant, depth) pairs; All descendants: recursive CTE / path <@ 'elektronika' + GiST / a plain JOIN; Moving a node: 1 row / update the path of the whole branch / delete and insert many rows…
📖 Answer
| adjacency list | ltree path |
closure table | |
|---|---|---|---|
| Parent | parent_id |
path = 'elektronika.telefon.smartfon' |
(ancestor, descendant, depth) pairs |
| All descendants | recursive CTE | path <@ 'elektronika' + GiST |
a plain JOIN |
| Moving a node | 1 row | update the path of the whole branch | delete and insert many rows |
| Integrity | FK is easy | no FK, the application maintains the path | a trigger or application code |
The adjacency list is the simplest and the right default:
WITH RECURSIVE sub AS (
SELECT id FROM category WHERE id = :root
UNION ALL
SELECT c.id FROM category c JOIN sub ON c.parent_id = sub.id
)
SELECT p.* FROM product p WHERE p.category_id IN (SELECT id FROM sub);
For a few thousand categories this takes milliseconds. The problem shows up when the tree is big (hundreds of thousands of nodes) and this query runs thousands of times a second.
With ltree, descendants are a single index query:
CREATE INDEX ON category USING gist (path);
SELECT * FROM category WHERE path <@ 'elektronika.telefon';
The cost: if "telefon" moves to a different parent, the path of the whole branch is rewritten. Catalog trees rarely change, so in e-commerce I often store parent_id and the ltree path together: integrity through the FK, fast lookup through the path.
I've used a closure table for deep, frequently queried hierarchies (an organizational structure, permissions). It works in any SQL database, but writes are complex.
Sign up to mark studied questions and save your progress.