by aidos · 14y ago · 0 comments
You're effectively working with a tree and there are much more relational friendly ways of doing that in SQL.
I know I'm just picking on this specific use but I can't help imagining that recursive querying will always be slow. Would love to hear how it's implemented if that's not the case.
Here is the query plan I got for my above query:
QUERY PLAN
CTE Scan on path (cost=292.79..304.41 rows=581 width=104)
CTE path
-> Recursive Union (cost=0.00..292.79 rows=581 width=72)
-> Index Scan using fs_pkey on fs (cost=0.00..8.27 rows=1 width=40)
Index Cond: (id = 1)
-> Hash Join (cost=0.33..27.29 rows=58 width=72)
Hash Cond: (public.fs.parent_id = parentpath.id)
-> Seq Scan on fs (cost=0.00..21.60 rows=1160 width=40)
-> Hash (cost=0.20..0.20 rows=10 width=36)
-> WorkTable Scan on path parentpath (cost=0.00..0.20 rows=10 width=36)Of course other options should always be considered. Joe Celko has a book on storing trees in the database I've been meaning to pick up.
It's all going to depend on your usecase but in general these sorts of path operations tend to be more read and less manipulation. You'll almost certainly get much faster lookups if you're not using recursive queries (as you can normally just use an index).