Difference between EXISTS and IN in SQL?

前端 未结 21 1812
执笔经年
执笔经年 2020-11-22 16:50

What is the difference between the EXISTS and IN clause in SQL?

When should we use EXISTS, and when should we use IN

21条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 17:31

    IN supports only equality relations (or inequality when preceded by NOT).
    It is a synonym to =any / =some, e.g

    select    * 
    from      t1 
    where     x in (select x from t2)
    ;
    

    EXISTS supports variant types of relations, that cannot be expressed using IN, e.g. -

    select    * 
    from      t1 
    where     exists (select    null 
                      from      t2 
                      where     t2.x=t1.x 
                            and t2.y>t1.y 
                            and t2.z like '℅' || t1.z || '℅'
                      )
    ;
    

    And on a different note -

    The allegedly performance and technical differences between EXISTS and IN may result from specific vendor's implementations/limitations/bugs, but many times they are nothing but myths created due to lack of understanding of the databases internals.

    The tables' definition, statistics' accuracy, database configuration and optimizer's version have all impact on the execution plan and therefore on the performance metrics.

提交回复
热议问题