Performance of SQL “EXISTS” usage variants

后端 未结 9 741
-上瘾入骨i
-上瘾入骨i 2020-12-05 04:39

Is there any difference in the performance of the following three SQL statements?

SELECT * FROM tableA WHERE EXISTS (SELECT * FROM tableB WHERE tableA.x = ta         


        
9条回答
  •  青春惊慌失措
    2020-12-05 05:29

    The truth about the EXISTS clause is that the SELECT clause is not evaluated in an EXISTS clause - you could try:

    SELECT * 
      FROM tableA 
     WHERE EXISTS (SELECT 1/0 
                     FROM tableB 
                    WHERE tableA.x = tableB.y)
    

    ...and should expect a divide by zero error, but you won't because it's not evaluated. This is why my habit is to specify NULL in an EXISTS to demonstrate that the SELECT can be ignored:

    SELECT * 
      FROM tableA 
     WHERE EXISTS (SELECT NULL
                     FROM tableB 
                    WHERE tableA.x = tableB.y)
    

    All that matters in an EXISTS clause is the FROM and beyond clauses - WHERE, GROUP BY, HAVING, etc.

    This question wasn't marked with a database in mind, and it should be because vendors handle things differently -- so test, and check the explain/execution plans to confirm. It is possible that behavior changes between versions...

提交回复
热议问题