Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 COUNT(*). Is that faster?

What about LIMIT 1?

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

Thanks in an advice!

like image 630
daGrevis Avatar asked Sep 27 '11 12:09

daGrevis


2 Answers

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)
like image 175
ypercubeᵀᴹ Avatar answered Oct 12 '22 23:10

ypercubeᵀᴹ


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)

like image 35
Chris G. Avatar answered Oct 13 '22 00:10

Chris G.