What's the difference between NOT EXISTS vs. NOT IN vs. LEFT JOIN WHERE IS NULL?

前端 未结 5 850
独厮守ぢ
独厮守ぢ 2020-11-22 00:56

It seems to me that you can do the same thing in a SQL query using either NOT EXISTS, NOT IN, or LEFT JOIN WHERE IS NULL. For example:

SELECT a FROM table1          


        
5条回答
  •  花落未央
    2020-11-22 01:09

    If the database is good at optimising the query, the two first will be transformed to something close to the third.

    For simple situations like the ones in you question, there should be little or no difference, as they all will be executed as joins. In more complex queries, the database might not be able to make a join out of the not in and not exists queryes. In that case the queries will get a lot slower. On the other hand, a join may also perform badly if there is no index that can be used, so just because you use a join doesn't mean that you are safe. You would have to examine the execution plan of the query to tell if there may be any performance problems.

提交回复
热议问题