Skip to content

Instantly share code, notes, and snippets.

@choplin
Created October 8, 2011 08:57
Show Gist options
  • Save choplin/1272045 to your computer and use it in GitHub Desktop.
Save choplin/1272045 to your computer and use it in GitHub Desktop.
DROP TABLE IF EXISTS t;
CREATE TABLE t (
id int PRIMARY KEY
,adj int[]
);
INSERT INTO t VALUES
(1, ARRAY[2,3,4,5])
,(2, ARRAY[1])
,(3, ARRAY[1,6])
,(4, ARRAY[1])
,(5, ARRAY[1,7])
,(6, ARRAY[3])
,(7, ARRAY[5]);
CREATE INDEX _idx_adj on t USING gin (adj);
WITH RECURSIVE r (id, adj, step) AS (
SELECT
*
,1
FROM
t
WHERE
id = 1
UNION ALL
SELECT
t.*
,r.step + 1
FROM
t,r
WHERE
t.id = ANY(r.adj) AND step < 3
)
SELECT
id
,array_agg(step)
FROM
r
GROUP BY
id
HAVING
array_agg(step) = ARRAY[3]
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment