views:

215

answers:

4

Currently I'm running these two queries:

SELECT COUNT(*) FROM `mytable`

SELECT * FROM `mytable` WHERE `id`=123

I'm wondering what format will be the most efficient. Does the order the queries are executed make a difference? Is there a single query that will do what I want?

+7  A: 

Both queries are fairly unrelated. The COUNT doesn't use any indexes, while the SELECT likely uses the primary key for a fast look-up. The only thing the queries have in common is the table.

Since these are so simple, the query optimizer and results cache shouldn't have a problem performing very well on these queries.

Are they causing you performance problems? If not, don't bother optimizing them.

Ben S
Well, not exactly. The whole data may not be cached. I believe it's better to use a primary key than *, since only the index file would be reached (all the requested data can be fetched from the index, so MySQL doesn't need to read the data file).Am I right?It also depends on the storage engine. MyISAM keeps a track of how many entries are stored inside the table. So SELECT COUNT(*) should be faster than SELECT pk.This is not true with InnoDB, where the whole index must be fetched to count the entries.
Savageman
+1  A: 

Does the order the queries are executed make a difference?

No, they reach for different things. The count will read a field that contains the number of colums of the table, the select by id will use the index. Both are fast and simple.

Is there a single query that will do what I want?

Yes, but it will make your code less clear, less maintenable (due to mixing concepts) and in the best case will not improve the performance (probably it will make it worse).

If you really really want to group them somehow, create a stored procedure, but unless you use this pair of queries a lot or in several places of the code, it can be an overkill.

Pere Villega
A: 

What table engine are you using?

select count(*) is better on MyISAM compare to InnoDB. In MyISAM the number of rows for each table is stored. When doing count(*) the value is return. InnoDB doesn't do this because it supports transactions.

More info: http://www.mysqlperformanceblog.com/2006/12/01/count-for-innodb-tables/

Yada
A: 

Hi DisgruntledGoat

First of: Ben S. makes a good point. This is not worth optimizing.

But if one wants to put those two statements in one SQl statement I think this is one way to do it:

select *,count(*) from mytable
union all
select *,-1 from mytable where id = 123

This will give one row for the count(*) (where one ignores all but the last column) and
as many rows where id = 123 (where one ignores the last column as it is always -1)

Like this:

 | Column1  | Column2  | Column3  | ColumnN  | Count(*) Column |
 ---------------------------------------------------------------
 | ignore   | ignore   | ignore   | ignore   |     4711        |
 |valid data|valid data|valid data|valid data|     -1 (ignore) |

Regards
    Sigersted

Sigersted