Question

I have a query that needs to check for existence of each input row type in another table, but it is unnecessary and inefficient to check for existence of subsequent rows of the same row type if one is already found.

I tried to reference the working table in an EXISTS subquery in the JOIN to prevent the unnecessary checks, but this gave an error that the recursive query cannot be referenced in a subquery.

For a simplified example modified from the docs only meant to demonstrate my problem in code:

WITH RECURSIVE t(n) AS (
    VALUES (1)
  UNION ALL
    SELECT n+1 FROM t WHERE n < 100 AND NOT EXISTS (SELECT 1 FROM t u WHERE u.n = t.n+1)
)
SELECT sum(n) FROM t;

This is of course logically ridiculous, but the NOT EXISTS is the problem and specifically what gives an error.

Is there a way to determine existence in the working table?

Was it helpful?

Solution

I'm not sure I fully understand what you expect to happen with the SQL you pasted .. (add up the numbers from 1-99 ignoring all even values?) But this is a SQL to get around the syntax error you have:

WITH RECURSIVE t(n) AS (
    VALUES (1)
  UNION ALL
    SELECT n+1 FROM t WHERE n+1 not in (t.n) and n < 100
)
SELECT sum(n) FROM t;

I would like to point out that the result of my SQL above returns 5050 because the "n+1" is never actually in the result set... (You'd need to compare for n-1 in the result set if you wanted to ignore even numbers..)

Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top