Count(*) vs Count(column_name)

Count(*) vs Count(column_name)

Count(*) vs Count(columng_name)

In SQL, COUNT(column_name) and COUNT(*) are both used with the COUNT function, but they have different behaviors:

  1. COUNT(column_name):

    • This form of COUNT counts the number of non-null values in the specified column.

    • It excludes NULL values from the count.

    • It is used when you want to count the number of non-null values in a specific column.

Example:

    SELECT COUNT(column_name) FROM your_table;

In this case, the result will be the count of non-null values in the specified column.

  1. COUNT(*):

    • This form of COUNT counts the number of rows in the result set, regardless of whether there are NULL values in any column.

    • It counts all rows, including those with NULL values.

Example:

    SELECT COUNT(*) FROM your_table;

In this case, the result will be the total number of rows in the table.

Here's a quick example to illustrate the difference:

Suppose you have a table employees:

employee_idsalary
150000
2NULL
360000
455000
5NULL
  • COUNT(salary) would give you the count of non-null salaries, which is 3.

  • COUNT(*) would give you the count of all rows, including those with NULL salaries, which is 5.

Choose the appropriate form based on your specific use case and what you want to achieve with the count. If you want to count all rows regardless of NULL values, use COUNT(*). If you want to count non-null values in a specific column, use COUNT(column_name).