Recursive version
@Dems beat me up: recursive CTE is the way to go . It works for any sequence of numbers. I submit my version because:
- This does not require an additional table. Just insert your consecutive numbers as an array.
- Recursive CTE in itself is simpler.
- The final request is smarter.
- It really works in PostgreSQL. The recursive version of @Dems is not syntactically correct in the current state.
Test setup:
CREATE TEMP TABLE t (id int, val int); INSERT INTO t VALUES (1,4),(2,5),(3,1) ,(4,5),(5,6),(6,1) ,(7,3),(8,2),(9,7);
Call:
WITH RECURSIVE x AS ( SELECT '{1,5,6,1,3}'::int[] AS a ), y AS ( SELECT t.id AS start_id ,1::int AS step FROM x JOIN t ON t.val = xa[1] UNION ALL SELECT y.start_id ,y.step + 1
Result:
3
Static version
Works for a predetermined number of array elements, but faster for small arrays. 5 items in this case. Same test setup as above.
WITH x AS ( SELECT '{1,5,6,1,3}'::int[] AS a ) SELECT t1.id FROM x, t t1 JOIN t t2 ON t2.id = t1.id + 1 JOIN t t3 ON t3.id = t1.id + 2 JOIN t t4 ON t4.id = t1.id + 3 JOIN t t5 ON t5.id = t1.id + 4 WHERE t1.val = xa[1] AND t2.val = xa[2] AND t3.val = xa[3] AND t4.val = xa[4] AND t5.val = xa[5];