Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between count(attribute) and count (*) using group by

Tags:

sql

I haven't understood the difference between count(*) and count having an attribute as argument.
Here I make an example: there are two relationships:

project (id, name, number);
employee (ssn, name, surname);
working_on (employee_ssn,   project_id);

With employee_ssn which references employee(ssn) and project_id referencing project(id).
Primary keys: project(id), employee(ssn), working_on (employee_ssn, project_id).
Now I have to find for each project, the id of the project, the name and the number of employees working on it.
A correct solution (found on the book) is this one:

select id, name, count (*)
from working_on join project on id=project_id
group by name, id

I have,'t understood why this solution is valid, shouldn't count (*) count all tuples? Why this way it gets the exact number of employees working on it?
I have written this solution instead:

select id, name, count (employee_ssn)
from working_on join project on id=project_id
group by name, id

Are the solutions equivalent?
And in general, there is a difference using count (*) and count(attribute)? Could you provide an example where these two syntaxes produce different results?

like image 303
Ramy Al Zuhouri Avatar asked Jun 07 '26 19:06

Ramy Al Zuhouri


1 Answers

From the documentation:

COUNT(expr)

Returns a count of the number of non-NULL values of expr in the rows retrieved by a SELECT statement.


COUNT(*) is somewhat different in that it returns a count of the number of rows retrieved, whether or not they contain NULL values.

In other words:

COUNT(expr) will return the number of rows that do not have a NULL value for expr.

COUNT(*) will return the total number of returned rows.

Whether or not you are using a GROUP BY clause is irrelevant.

like image 80
Evan Mulawski Avatar answered Jun 10 '26 19:06

Evan Mulawski