Skip to content

Instantly share code, notes, and snippets.

@nobishino
Last active December 21, 2019 05:21
Show Gist options
  • Save nobishino/dac5df7308bd7820736205fd156ea656 to your computer and use it in GitHub Desktop.
Save nobishino/dac5df7308bd7820736205fd156ea656 to your computer and use it in GitHub Desktop.

DDL

CREATE TABLE vertex (
    id       INTEGER PRIMARY KEY AUTOINCREMENT,
    parent_id INTEGER
);

Data

INSERT INTO vertex (ID, PARENT_ID)
VALUES

(1,1),
(2,1),
(3,1),
(4,1),
(5,2),
(6,2),
(7,3),
(8,7),
(9,3),
(10,7);

Query(SQLite3)

with recursive cte as (
    select * from vertex where id = 3
    union all
    select vertex.* from vertex
    inner join cte on vertex.parent_id = cte.id 
)
select * from cte
id parent_id
3 1
7 3
9 3
8 7
10 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment