Search code examples
sqlazure-sql-databasesql-null

SQL Count NULL values is 0 even when there are NULL values


In a particular case I have a database table populated with 1070 items, and at some point in the process I add a column called 'Current_Status' to it. As a result, all items have a new field that is initially NULL.

This table is used as a queue, and for each row that is processed, I update the 'Current_Status' field to 'Processed' or 'Non processed'.

In order to see how is the process going, I was counting the remaining items that still had the status NULL using this query:

SELECT COUNT([Current_Status]) FROM Table_Name WHERE [Current_Status] IS NULL

The issue is that after the first 1000 items, the result for that query execution was 0, even if I checked and using a SELECT * FROM Table_Name query shown that there where still some rows with status NULL.

Any ideas what might be causing this?

I checked this situation using Azure Data Studio 1.4.5.


Solution

  • The reason for that is because you have provided count with a column value which is null. Instead, use count(*):

    SELECT COUNT(*) FROM Table_Name WHERE [Current_Status] IS NULL
    

    Sample data:

    current_status
    --------------
    Processed
    Null
    Not Processed
    Null
    

    And the difference between two queries:

    count(current_status)

    SELECT count(current_status) FROM table_name WHERE current_status IS NULL 
    
    0
    

    count(*)

    SELECT count(*) FROM table_name WHERE current_status IS NULL 
    
    2