Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I COUNT(*) or not?

I know it's generally a bad idea to do queries like this:

SELECT * FROM `group_relations` 

But when I just want the count, should I go for this query since that allows the table to change but still yields the same results.

SELECT COUNT(*) FROM `group_relations` 

Or the more specfic

SELECT COUNT(`group_id`) FROM `group_relations` 

I have a feeling the latter could potentially be faster, but are there any other things to consider?

Update: I am using InnoDB in this case, sorry for not being more specific.

like image 685
grapefrukt Avatar asked Jan 19 '09 11:01

grapefrukt


People also ask

Which is better count (*) or Count 1?

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. The semantics for COUNT(1) differ slightly; we'll discuss them later. However, the results for COUNT(*) and COUNT(1) are identical.

Why select * is not recommended?

By using SELECT * , you can return unnecessary data that will just be ignored. But fetching that data is not free of cost. This results in some wasteful IO cycles on the DB end since you will be reading all of that data off the pages. Perhaps you could have read the data from index pages.

Why do we use count (*)?

The COUNT(*) function counts all the rows from Person. Person table. When we use an expression in the COUNT(Middlename), this returns the number of rows with a MiddleName value that is not null. In this case, the COUNT doesn't include null values in its total.

What is the use of count (*) in SQL?

COUNT(*) returns the number of rows in a specified table, and it preserves duplicate rows. It counts each row separately. This includes rows that contain null values.


2 Answers

If the column in question is NOT NULL, both of your queries are equivalent. When group_id contains null values,

select count(*) 

will count all rows, whereas

select count(group_id) 

will only count the rows where group_id is not null.

Also, some database systems, like MySQL employ an optimization when you ask for count(*) which makes such queries a bit faster than the specific one.

Personally, when just counting, I'm doing count(*) to be on the safe side with the nulls.

like image 138
pilif Avatar answered Sep 24 '22 23:09

pilif


If I remember it right, in MYSQL COUNT(*) counts all rows, whereas COUNT(column_name) counts only the rows that have a non-NULL value in the given column.

like image 42
Sebastian Dietz Avatar answered Sep 24 '22 23:09

Sebastian Dietz