Is EXISTS more efficient than COUNT(*)>0?

二次信任 提交于 2019-11-28 19:13:32

Yes, MySQL (indeed all database systems as far as I'm aware) will stop processing when a row is returned when using an Exists function.

You can read more at the MySQL documentation: If a subquery returns any rows at all, EXISTS subquery is TRUE.

I have run a test with 1000 queries. SELECT EXISTS was about 25% faster than SELECT COUNT. Adding limit 1 to SELECT COUNT did not make any difference.

The most reliable way is probably LIMIT 1, but that's not the point.

Provided you have an index like CREATE INDEX mytable_index_a_b ON mytable (a,b), MySQL should be smart enough to return the count from the index and not touch any rows at all. The benefit of LIMIT 1 is probably negligible.

If you don't have an index on (a,b), then performance will be terrible. LIMIT 1 may make it significantly less terrible, but it'll still be terrible.

This might be an approach too.

select 1 from mytable where a = "foo" and b = "bar" limit 1;

This would not traverce all records that meet the where condition but rather return '1' after first 'hit'. The drawback is you need to check for result, because there might be empty record set in return.

I don't know how well this works for optimization, but it should work functionally the same as exists. Exception being that it will return no row if there is no match.

SELECT true from mytable where a = "foo" and b = "bar" LIMIT 1;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!