-- Oracle -- WITH t1 AS ( SELECT 'a' col1, 'y' run_yn FROM dual UNION ALL SELECT 'b', '' FROM dual UNION ALL SELECT 'c', '' FROM dual UNION ALL SELECT 'd', '' FROM dual UNION ALL SELECT 'e', '' FROM dual UNION ALL SELECT 'f', '' FROM dual UNION ALL SELECT 'g', 'y' FROM dual ) , t2 AS ( SELECT 'a' col1, 'b' next_col FROM dual UNION ALL SELECT 'b', 'c' FROM dual UNION ALL SELECT 'c', 'd' FROM dual UNION ALL SELECT 'e', 'f' FROM dual ) SELECT a.col1 FROM t1 a LEFT OUTER JOIN t2 b ON a.col1 = b.next_col WHERE a.run_yn IS NULL START WITH b.col1 IS NULL CONNECT BY PRIOR a.col1 = b.col1 AND PRIOR a.run_yn = 'y' ;
-- PostgreSQL -- WITH RECURSIVE t4 AS ( WITH t1 AS ( SELECT 'a' col1, 'y' run_yn UNION ALL SELECT 'b', null UNION ALL SELECT 'c', null UNION ALL SELECT 'd', null UNION ALL SELECT 'e', null UNION ALL SELECT 'f', null UNION ALL SELECT 'g', 'y' ) , t2 AS ( SELECT 'a' col1, 'b' next_col UNION ALL SELECT 'b', 'c' UNION ALL SELECT 'c', 'd' UNION ALL SELECT 'e', 'f' ) , t3 AS ( SELECT a.col1 , b.col1 p_col1 , a.run_yn FROM t1 a LEFT OUTER JOIN t2 b ON a.col1 = b.next_col ) SELECT * FROM t3 WHERE p_col1 IS NULL UNION ALL SELECT b.* FROM t4 a INNER JOIN t3 b ON a.col1 = b.p_col1 WHERE a.run_yn = 'y' ) SELECT col1 FROM t4 WHERE run_yn IS NULL ;