7

Here's my table.
info.student_info table

When I execute the below query using NOT IN it gives me namal and Ann.

SELECT firstname 
FROM info.student_info 
WHERE firstname NOT IN (SELECT firstname 
                        FROM info.student_info 
                        WHERE lastname IS NULL)

But when I execute the below query using NOT EXISTS it gives me no rows.

SELECT firstname 
FROM info.student_info 
WHERE NOT EXISTS (SELECT firstname 
                  FROM info.student_info 
                  WHERE lastname IS NULL)

Why is this? I have researched some areas on NOT IN and NOT EXISTS, but couldn't find an answer for this.

2
  • 1
    In the second case, the correlated subquery is not corelated to the main query; it returns True if there does not exist any row with lastname IS NULL. Commented Jan 29, 2014 at 9:34
  • The usual answer is NULL, but your NOT IN already filters out NULLs. @wildplasser accurately points out the difference. Commented Jan 29, 2014 at 9:37

3 Answers 3

22

NOT IN is true when value is not in the set returned by the subquery. NOT EXISTS is true when the subquery doesn't return anything.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Jakub. It tell's everything!
4

You have not joined the tables in your NOT EXISTS query and that is why, you're not getting any result from your second query.

Your second query would have returned results only in case when the sub-query could not find record at all.

change your query to join on the firstname column of the outer table, and then you might get result.

SELECT firstname
FROM info.student_info
WHERE NOT EXISTS (SELECT b.firstname
                  FROM   info.firstname b
                  WHERE  b.lastname IS NULL
                  AND    b.firstname = a.firstname
                 )

Disclaimer: Not tested the query

Comments

3

Your NOT EXISTS doesn't discriminate on firstname, so the subselect will always return 2 rows.

To do the same thing with NOT EXISTS you need to use the following SQL:

SELECT firstname FROM info.student_info 
WHERE NOT EXISTS 
  (SELECT firstname f2 FROM info.student_info
    WHERE lastname IS NULL 
      AND f2 = firstname)

1 Comment

Thank you! Honestly, I had an misunderstanding on the IN and EXISTS. I was enlightened with Jakub's answer. Apart from that here the result is same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.