Reputation: 737
I have table with around 60 000 rows. I have this two queries that are drastically different in speed. Can you explain why?
SELECT COUNT(id) FROM table;
300ms - 58936 rows
Explain:
id | select_type | table | partitions | type | possible_keys | key | key_length | ref | rows | filtered | Extra |
---|---|---|---|---|---|---|---|---|---|---|---|
1 | SIMPLE | table | NULL | index | NULL | table_id_index | 8 | NULL | 29325 | 100.00 | using index |
SELECT COUNT(id) FROM table WHERE dummy = 1;
50ms - 58936 rows
Explain:
id | select_type | table | partitions | type | possible_keys | key | key_length | ref | rows | filtered | Extra |
---|---|---|---|---|---|---|---|---|---|---|---|
1 | SIMPLE | table | NULL | index | NULL | dummy_index | 5 | const | 14662 | 100.00 | using index |
Upvotes: 1
Views: 169
Reputation: 142296
It depends.
COUNT(id)
may be slower than COUNT(*)
. The former checks id
for being NOT NULL
; the latter simply counts the rows. (If id
is the PRIMARY KEY
, then this is unlikely to make any measurable difference.)WHERE
clause. In your example, any index with id
can be used for the first, and any index with both dummy
and id
for the second.EXPLAIN SELECT ...
INDEX(dummy, id)
.Upvotes: 3