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 COUNT(*)
. 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With