André
André

Reputation: 25554

MySQL - It is possible to speed up MySQL count?

I have a simple query like:

select count(*) from table

Can I speed up MySQL by doing:

select count(id) from table

Does this make any difference in terms of speed?

Best Regards,

Upvotes: 1

Views: 381

Answers (4)

MarkR
MarkR

Reputation: 63538

If id is "not null", no it won't make any difference.

If id is nullable, then it is a different query and will not (always) produce the same result.

Upvotes: 0

Rich O'Kelly
Rich O'Kelly

Reputation: 41757

If id is your primary key, then no it will not, since MySql will use the primary key under the covers anyway. If id is not the primary key, then it may actually make the query slightly slower.

Upvotes: 0

ajreal
ajreal

Reputation: 47321

You can try to get the count from information_schema

select TABLE_ROWS from information_schema.tables
where TABLE_SCHEMA = '$db' and TABLE_NAME = '$tbl'; 

Upvotes: 1

Tom van der Woerdt
Tom van der Woerdt

Reputation: 29975

Not if id is your primary key. * will simply map to your primary key. count(id) = count(*)

Upvotes: 1

Related Questions