When using COUNT (DISTINCT fieldA), does it rule out counting NULL values that would be in fieldA
The DISTINCT operator treats NULL duplicate. It means that the two NULLs are the same. Therefore, if the SELECT statement returns NULL s, the DISTINCT returns only one NULL .
If the COUNT DISTINCT function encounters NULL values, it ignores them unless every value in the specified column is NULL. If every column value is NULL, the COUNT DISTINCT function returns zero (0).
The SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.
You Kind of have 2 questions between your title and your narrative.
DISTINCT does NOT eliminate (rule out) Nulls
However
Aggregate Functions IGNORE Null Values
As others have mentioned so if you want to count all NON NULL DISTINCT Values use the code you mentioned.
SELECT COUNT(DISTINCT columnName)
If you want to count all nulls as another value you can do that 1 of 2 ways.
1) Use COALESCE() to eliminate the null with a value that is not represented within your dataset. E.g.
SELECT COUNT(DISTINCT COALESCE(columnName,'|||||||||'))
2) the more certain way use conditional aggregation similar to what Gordon showed:
To show how distinct does not eliminate null values:
CREATE TABLE DistinctTest (Col INT)
INSERT INTO DistinctTest (Col) VALUES (NULL),(1),(2),(3),(NULL)
SELECT DISTINCT *
FROM
DistinctTest
Yes, it ignores NULL
s. If you want to include NULL
s, then this is a safe way:
SELECT COUNT(DISTINCT fieldA) + MAX(CASE WHEN fieldA IS NULL THEN 1 ELSE 0 END)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With