3

Table1

Id Name  DemoID
1  a      33
2  b      44
3  c      33
4  d      33
5  e      44

Table2

Id DemoID IsTrue
11  33     1  
12  44     1

Table3

Id Table1_ID
11  1  

Now we can find which DemoID is present in Table2 using below query -

SELECT Table1.Id FROM Table1 as Table1
WHERE EXISTS
(
   SELECT * FROM Table2 as Table2
   WHERE Table1.DemoID  = Table2.DemoID AND Table2.IsTrue= 1
)

result - 1,2,3,4,5

But I also want to check into 3rd table whether those records are EXISTS OR NOT. using one more condition NOT EXISTS in same query ?

for example Table3 has Table1_ID column value only 1 now new NOT exist query should give me result 2,3,4,5

I tried like -

SELECT Table1.Id FROM Table1 as Table1
    WHERE EXISTS
    (
       SELECT * FROM Table2 as Table2
       WHERE Table1.DemoID  = Table2.DemoID AND Table2.IsTrue= 1
    )
AND NOT EXISTS (SELECT * FROM Table3)

but it is giving me no records. it should give me remaining records those are 2,3,4,5

0

1 Answer 1

12

The condition:

NOT EXISTS (SELECT * FROM Table3)

...is always false if there are any rows in Table3, so your query returns no rows.

You need to add a predicate to show how Table3 rows are qualified, as shown in bold below:

SELECT Table1.Id
FROM Table1 AS Table1
WHERE EXISTS
    (
        SELECT 1 
        FROM Table2 AS Table2
        WHERE
            Table1.DemoID  = Table2.DemoID 
            AND Table2.IsTrue= 1
    )
    AND NOT EXISTS
    (
        SELECT 1
        FROM Table3
        WHERE
            Table3.Table1_ID = Table1.Id -- New
    );

Demo: db<>fiddle

Not the answer you're looking for? Browse other questions tagged or ask your own question.