Skip to content

Instantly share code, notes, and snippets.

@knmkr
Created March 16, 2015 09:12
Show Gist options
  • Save knmkr/b104e543e01ce67dc03b to your computer and use it in GitHub Desktop.
Save knmkr/b104e543e01ce67dc03b to your computer and use it in GitHub Desktop.
PostgreSQL WITH RECURSIVE example
DROP TABLE IF EXISTS my_tree;
CREATE TABLE my_tree (id integer, parent integer);
INSERT INTO my_tree VALUES (1, null), (2, 1), (3, 1), (4, 3);
--
-- 1
-- / \
-- 2 3
-- |
-- 4
WITH RECURSIVE r AS (
SELECT * FROM my_tree WHERE id = 1
UNION ALL
SELECT my_tree.* FROM my_tree, r WHERE my_tree.parent = r.id
)
SELECT * FROM r ORDER BY id;
-- http://lets.postgresql.jp/documents/technical/with_recursive
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment