Home >Database >Mysql Tutorial >COUNT(*) vs. COUNT(Column-Name): When Should I Use Which Aggregate Function?

COUNT(*) vs. COUNT(Column-Name): When Should I Use Which Aggregate Function?

DDD
DDDOriginal
2025-01-07 07:56:43646browse

COUNT(*) vs. COUNT(Column-Name): When Should I Use Which Aggregate Function?

COUNT(*) vs COUNT(Column-Name): Determining the Appropriate Aggregate Function

In SQL, determining which aggregate function to use between COUNT() and COUNT(column-name) is an essential aspect of data retrieval. Whether the choice of COUNT() or COUNT(column-name) matters hinges on the desired result.

COUNT(*) calculates the total number of rows in a result set, regardless of whether specific columns contain NULL values. In contrast, COUNT(column-name) only counts non-NULL values within the specified column.

To further clarify:

  • COUNT(*): Encompasses all rows, including those with NULL values.
  • COUNT(column-name): Excludes rows with NULL values in the specified column.
  • COUNT(1): Functionally equivalent to COUNT(*) since 1 represents a non-NULL expression.

The appropriate function to employ depends solely on the intended output. If you seek a total count of all rows, regardless of NULL values, COUNT(*) suffices. However, if you aim to count only non-NULL values in a specific column, COUNT(column-name) is the preferred choice.

The above is the detailed content of COUNT(*) vs. COUNT(Column-Name): When Should I Use Which Aggregate Function?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn