Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

COUNT(id) vs. COUNT(*) in MySQL

Tags:

sql

mysql

count

Is there a difference between the following queries, assuming there is a primary field 'id' in the table (as in speed, etc)?

SELECT COUNT(id)    FROM table 

vs.

SELECT COUNT(*)    FROM table 
like image 208
James Simpson Avatar asked Nov 08 '09 16:11

James Simpson


People also ask

Which is faster COUNT (*) or COUNT ID?

The simple answer is no – there is no difference at all. The COUNT(*) function counts the total rows in the table, including the NULL values.

What is the difference between COUNT (*) and COUNT () in MySQL?

The count(*) returns all rows whether column contains null value or not while count(columnName) returns the number of rows except null rows. Let us first create a table.

What is COUNT ID?

In this case, COUNT(id) counts the number of rows in which id is not NULL .

What is COUNT (*) in MySQL?

MySQL COUNT() Function The COUNT() function returns the number of records returned by a select query.


1 Answers

I know this question is about MySQL, but for what it's worth, count(*) is recommended for Oracle, which goes to show that the answer to this can be database dependent (see comment above from BalusC).

Since a lot of databases (MS-SQL, MySQL) have information schema tables that hold various types of metadata, there are bound to be differences if one syntax is simply looking up a readily-available value, and another is going straight to the table.

At the end of day: try different options, and see what EXPLAIN is telling you is going on behind the scenes.

like image 79
davek Avatar answered Sep 20 '22 15:09

davek