开发者

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

I'm looking for the fastest way to check that entry exists...

All my life, I did with something like this...

SELECT COUNT(`id`) FROM `table_name`

Some people don't use COUNT(id), but COUN开发者_如何学PythonT(*). Is that faster?

What about LIMIT 1?

P.S. With id I meant primary key, of course.

Thanks in an advice!


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜