What's the fastest way to check that entry exists in database?

此生再无相见时 提交于 2019-12-05 06:21:26

In most situations, COUNT(*) is faster than COUNT(id) in MySQL (because of how grouping queries with COUNT() are executed, it may be optimized in future releases so both versions run the same). But if you only want to find if at least one row exists, you can use EXISTS

simple:

( SELECT COUNT(id) FROM table_name ) > 0

a bit faster:

( SELECT COUNT(*) FROM table_name ) > 0

much faster:

EXISTS (SELECT * FROM table_name)

If you aren't worried about accuracy, explain select count(field) from table is incredibly fast.

http://www.mysqlperformanceblog.com/2007/04/10/count-vs-countcol/

This link explains the difference between count(*) and count(field). When in doubt, count(*)

As for checking that a table is not empty...

SELECT EXISTS(SELECT 1 FROM table)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!