Mysql Exists vs IN — correlated subquery vs subquery?

前端 未结 3 1835
一生所求
一生所求 2020-12-09 05:33

I\'m curious about how the execution of EXISTS() is supposed to be faster than IN().

I was answering a question when Bill Karwin brought up

3条回答
  •  温柔的废话
    2020-12-09 05:58

    As you already know, a subquery does not use values from the outer query, thus it is executed only once. The correlated subquery is synchronized, thus it is executed for every row processed in the outer query.

    The advantage of using EXISTS is that, if it considered to be met, the execution of the subquery stops after returning at least one row. So, it can be quicker than a simple subquery. But it's not a general rule! All depend on the query your are executing, the query optimizer, and the SQL execution engine version.

    EXISTS is recommended to be used when you have e.g an if conditional statement, because it is certainly quicker than count.

    You can't really compare both subqueries using a simple benchmark of 4 or 3 queries.

    Hope it's useful!

提交回复
热议问题