Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In SQL, what's the difference between count(column) and count(*)?

Tags:

sql

I have the following query:

select column_name, count(column_name)
from table
group by column_name
having count(column_name) > 1;

What would be the difference if I replaced all calls to count(column_name) to count(*)?

This question was inspired by How do I find duplicate values in a table in Oracle?.


To clarify the accepted answer (and maybe my question), replacing count(column_name) with count(*) would return an extra row in the result that contains a null and the count of null values in the column.

like image 708
Bill the Lizard Avatar asked Sep 26 '22 04:09

Bill the Lizard


People also ask

What is difference between count (*) and count column in SQL?

Difference between count(*) and count(columnName) 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.

What does count * Mean SQL?

COUNT(*) does not require an expression parameter because by definition, it does not use information about any particular column. 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.

What is difference between count (*) and Count 1?

The difference is simple: COUNT(*) counts the number of rows produced by the query, whereas COUNT(1) counts the number of 1 values. Note that when you include a literal such as a number or a string in a query, this literal is "appended" or attached to every row that is produced by the FROM clause.

What is meant by count (*)?

count(*) means it will count all records i.e each and every cell BUT. count(1) means it will add one pseudo column with value 1 and returns count of all records.


2 Answers

count(*) counts NULLs and count(column) does not

[edit] added this code so that people can run it

create table #bla(id int,id2 int)
insert #bla values(null,null)
insert #bla values(1,null)
insert #bla values(null,1)
insert #bla values(1,null)
insert #bla values(null,1)
insert #bla values(1,null)
insert #bla values(null,null)

select count(*),count(id),count(id2)
from #bla

results 7 3 2

like image 248
SQLMenace Avatar answered Oct 08 '22 05:10

SQLMenace


Another minor difference, between using * and a specific column, is that in the column case you can add the keyword DISTINCT, and restrict the count to distinct values:

select column_a, count(distinct column_b)
from table
group by column_a
having count(distinct column_b) > 1;
like image 37
Brannon Avatar answered Oct 08 '22 05:10

Brannon