How do SQL EXISTS statements work?

前端 未结 7 494
不知归路
不知归路 2020-12-04 05:20

I\'m trying to learn SQL and am having a hard time understanding EXISTS statements. I came across this quote about \"exists\" and don\'t understand something:

相关标签:
7条回答
  • 2020-12-04 06:17

    It appears to me that there is no relationship between the outer query and the subquery.

    What do you think the WHERE clause inside the EXISTS example is doing? How do you come to that conclusion when the SUPPLIERS reference isn't in the FROM or JOIN clauses within the EXISTS clause?

    EXISTS valuates for TRUE/FALSE, and exits as TRUE on the first match of the criteria -- this is why it can be faster than IN. Also be aware that the SELECT clause in an EXISTS is ignored - IE:

    SELECT s.*
      FROM SUPPLIERS s
     WHERE EXISTS (SELECT 1/0
                     FROM ORDERS o
                    WHERE o.supplier_id = s.supplier_id)
    

    ...should hit a division by zero error, but it won't. The WHERE clause is the most important piece of an EXISTS clause.

    Also be aware that a JOIN is not a direct replacement for EXISTS, because there will be duplicate parent records if there's more than one child record associated to the parent.

    0 讨论(0)
提交回复
热议问题