Weird working of correlated query - Is this SQL correct?

99 views Asked by At

Please check the below query:

with sd as 
(
    select 1 id, 'abc' col from dual
    union
    select 2 id, 'xyz' col from dual
    union
    select 3 id, 'pqr' col from dual
),
t as 
(
    select 1 id, '123' col2 from dual
    union
    select 2 id, '233' col2 from dual
    union
    select 4 id, '456' col2 from dual
)
SELECT 
    id,
    col2,
    (SELECT 'ok' FROM dual WHERE SD_EXIST = 'Y') CHECK_CON
    --,SD_EXIST
FROM 
    (SELECT
         id,
         col2,
         CASE 
             WHEN EXISTS (SELECT 1 FROM sd WHERE sd.id = t.id)
                 THEN 'Y' 
                 ELSE NULL 
         END AS SD_EXIST
     FROM
         t) ;

There are 2 views defined - sd and t.

Final query inline view should return this result:

ID COL2 SD_EXIST
----------------
1   123   Y
2   233   Y
4   456   -

But the output of final query CHECK_CON column changes.

– if SD_EXIST is included in projection of select, CHECK_CON is null (for id 456) - Here the query behavior is working fine.

  • if SD_EXIST is commented (not included in projection of select), CHECK_CON is OK (for id 456)- Here output is different and shows weird behavior of the query.

How does this work? I want understand the logic and working behind this and how it shows different results.

enter image description here

0

There are 0 answers