What is the difference between COUNT(*) and COUNT(column_name) when counting rows with NULLs?

Study for the SQL Basics Test. Improve your knowledge with multiple choice questions and detailed explanations. Prepare effectively to master SQL concepts!

Multiple Choice

What is the difference between COUNT(*) and COUNT(column_name) when counting rows with NULLs?

Explanation:
Counting with COUNT(*) looks at every row, regardless of NULLs in any column. It counts the total number of rows returned by the query (or after a WHERE/GROUP BY, the rows in that group). In contrast, COUNT(column_name) counts only the non-null values in that specific column; rows where column_name is NULL are not included in the count. For example, if a table has three rows and the values in column_name are 5, NULL, and 7, COUNT(*) would be 3, while COUNT(column_name) would be 2. Use COUNT(*) when you want the total row count; use COUNT(column_name) to count how many rows have a non-null value in that column.

Counting with COUNT(*) looks at every row, regardless of NULLs in any column. It counts the total number of rows returned by the query (or after a WHERE/GROUP BY, the rows in that group). In contrast, COUNT(column_name) counts only the non-null values in that specific column; rows where column_name is NULL are not included in the count.

For example, if a table has three rows and the values in column_name are 5, NULL, and 7, COUNT() would be 3, while COUNT(column_name) would be 2. Use COUNT() when you want the total row count; use COUNT(column_name) to count how many rows have a non-null value in that column.

Subscribe

Get the latest from Passetra

You can unsubscribe at any time. Read our privacy policy