I am wondering if there is a performance difference between these two queries that check if a record exists?
select count(1) from table where id = 1;
or
select id from table where id = 1;
I am wondering if there is a performance difference between these two queries that check if a record exists?
select count(1) from table where id = 1;
or
select id from table where id = 1;
The second statement is probably faster. But for practical purposes, the difference will be negligible
I don't think there will be much of a difference between those two queries : the difference being selecting a field (which is part of an index) in the second case, and counting one line in the first... Not that much of a difference.
Still, out of curiosity, I did a very quick benchmark of those kind of queries on a database I have on my computer -- note there are only like 7 lines in the post table, so it might not be that close to a real situation, but as there is a PK on id
, which means an index....
Here's what I got :
mysql> select benchmark(10000000000, 'select sql_no_cache id from post where id = 1');
+-------------------------------------------------------------------------+
| benchmark(10000000000, 'select sql_no_cache id from post where id = 1') |
+-------------------------------------------------------------------------+
| 0 |
+-------------------------------------------------------------------------+
1 row in set (1 min 0,25 sec)
mysql> select benchmark(10000000000, 'select sql_no_cache count(1) from post where id = 1');
+-------------------------------------------------------------------------------+
| benchmark(10000000000, 'select sql_no_cache count(1) from post where id = 1') |
+-------------------------------------------------------------------------------+
| 0 |
+-------------------------------------------------------------------------------+
1 row in set (1 min 0,23 sec)
So, really not that much of a difference, it seems ^^