Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count(*) and count(column_name), what's the diff?

Tags:

mysql

count(*) and count(column_name), what's the difference in mysql.

like image 932
lovespring Avatar asked May 20 '10 18:05

lovespring


People also ask

What is the difference between count (*) and count attribute?

count() only counts non-null values. * references the complete row and as such never excludes any rows. count(attribute_name) only counts rows where that column is no null. so that means if I use count(attribute_name), it will count all data in the table even if the row has no data.

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.

What is the difference between count (*) count expression count distinct expression )?

COUNT ( * ) counts all the rows in the target table whether they include nulls or not. COUNT ( expression ) computes the number of rows with non-NULL values in a specific column or expression. COUNT ( DISTINCT expression ) computes the number of distinct non-NULL values in a column or expression.

What is the difference between count (*) and count in SQL give example?

COUNT(*) returns the number of items in a group. This includes NULL values and duplicates. COUNT(ALL expression) evaluates expression for each row in a group, and returns the number of nonnull values.


1 Answers

  • COUNT(*) counts all rows in the result set (or group if using GROUP BY).
  • COUNT(column_name) only counts those rows where column_name is NOT NULL. This may be slower in some situations even if there are no NULL values because the value has to be checked (unless the column is not nullable).
  • COUNT(1) is the same as COUNT(*) since 1 can never be NULL.

To see the difference in the results you can try this little experiment:

CREATE TABLE table1 (x INT NULL);
INSERT INTO table1 (x) VALUES (1), (2), (NULL);
SELECT
    COUNT(*) AS a,
    COUNT(x) AS b,
    COUNT(1) AS c
FROM table1;

Result:

a   b   c
3   2   3
like image 62
Mark Byers Avatar answered Oct 16 '22 20:10

Mark Byers