Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a hierarchical tree path in SQLite?

Tags:

sqlite

tree

Imagine a simple table that defines a tree structure.

create table nodes (
    id integer primary key,
    name text not null,
    parent integer
)

Some example nodes:

enter image description here

Node 1 is parent of 2 and 3. Node 3 is parent of 4. Is it possible to write a SQL query in SQLite, so that it returns:

id    path
1     foo
2     foo/bar
3     foo/baz
4     foo/baz/stuff
like image 370
Rob N Avatar asked Sep 17 '25 17:09

Rob N


1 Answers

You can perform recursion in SQLite using recursive common table expressions.

An example query that would return the node paths:

with recursive paths(id, name, path) as (
    select id, name, name from nodes where parent is null
    union
    select nodes.id, nodes.name, paths.path || '/' || nodes.name
    from nodes join paths where nodes.parent = paths.id
)
select id, path from paths
like image 69
Rob N Avatar answered Sep 20 '25 09:09

Rob N