Search code examples
sqlsql-serverexistsnot-exists

NOT IN vs NOT EXISTS and select 1 1?


I am very much a beginner and I completely get what NOT IN does, but don't really get EXISTS or NOT EXISTS. Even more, I don't understand what this does:

SELECT TOP 1 1 
FROM tblSomeTable

What does this query actually do?

For reference, I have been working with something like this:

SELECT COUNT(E_ID)
FROM  tblEmployee e    
INNER JOIN  tblManager m 
      ON e.tbl_ID = m.tbl_ID         
WHERE NOT EXISTS(SELECT TOP 1 1 
                   FROM tblEmployee e2 
                   WHERE e2.E_ID = e.E_ID 
                       AND isFired = 'N'
                   )

I suppose I haven't read/seen a layman's explanation yet that makes sense to me. Even after reading Diff between Top 1 1 and Select 1 in SQL Select Query I still don't get it


Solution

  • Your first query will get you only top most record (very first record) out of the total rows in result set. So, if your query returns 10 rows .. you will get the first row. Read more about TOP

    SELECT TOP 1 FROM tblSomeTable
    

    In your Second query the part under () is a subquery, in your case it's a correlated subquery which will be evaluated once for each row processed by the outer query.

    NOT EXISTS will actually check for existence of the rows present in subquery

    WHERE NOT EXISTS
    (
    SELECT TOP 1 1 FROM tblEmployee e2 WHERE e2.E_ID = e.E_ID AND isFired = 'N'
    )
    

    Read more about Correlated subquery as well as Subqueries with EXISTS