Home > Database > Mysql Tutorial > COUNT(*) vs. COUNT(column-name): Which SQL Aggregate Function Should I Use?

COUNT(*) vs. COUNT(column-name): Which SQL Aggregate Function Should I Use?

Patricia Arquette
Release: 2025-01-07 08:06:40
Original
320 people have browsed it

COUNT(*) vs. COUNT(column-name): Which SQL Aggregate Function Should I Use?

Which is More Correct: COUNT(*) vs. COUNT(column-name)?

The SQL aggregate function COUNT can be used in two ways: COUNT(*) and COUNT(column-name). While both methods aim to tally the number of rows, there are subtle differences to consider.

COUNT(*)

  • Counts all rows, even those with NULL values.
  • Useful when obtaining a total count of records without regard to data availability.

COUNT(column-name)

  • Counts non-NULL values only.
  • More specific and can be used to count the number of rows with a particular value or to filter out NULLs.

In your example code:

  • COUNT(*): Counts all rows in the group, including any with missing values.
  • COUNT(customerid): Counts only rows with customer IDs. It filters out any rows with NULL customer IDs.

Choosing between COUNT(*) and COUNT(column-name) depends on the desired output:

  • To count the total number of rows, regardless of NULLs, use COUNT(*).
  • To count non-NULL values only, use COUNT(column-name).

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template