Mysql NOT IN and NOT EXIST the same?

后端 未结 4 1723
再見小時候
再見小時候 2021-01-12 07:36

I sometimes interchanged the use of NOT IN and NOT EXIST in my sql queries and both yield the same result. Is the logic behind the NOT EXIST

4条回答
  •  北恋
    北恋 (楼主)
    2021-01-12 08:35

    Both will give you the same results. The NOT EXISTS is a correlated sub-query, it is joined to the main query. In the example below, the NOT EXISTS should perform faster on a large dataset.

    Find products without orders.

    select *
      from Products
     where ProductId NOT IN (select ProductId FROM Orders)
    
    select *
      from Products
     where NOT EXISTS (select 1 FROM Orders WHERE orders.ProductId = Products.Id)
    

提交回复
热议问题