count(*)
and count(column_name)
, what's the difference in mysql.
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.
The difference is simple: COUNT(*) counts the number of rows produced by the query, whereas COUNT(1) counts the number of 1 values.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With