Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does DISTINCT rule out Nulls

Tags:

sql

ssms

When using COUNT (DISTINCT fieldA), does it rule out counting NULL values that would be in fieldA

like image 494
luke Avatar asked Sep 14 '16 17:09

luke


People also ask

Does distinct get rid of NULLs?

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 .

Does distinct consider NULL values?

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).

What does SELECT distinct do?

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.


2 Answers

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
like image 165
Matt Avatar answered Oct 24 '22 02:10

Matt


Yes, it ignores NULLs. If you want to include NULLs, then this is a safe way:

SELECT COUNT(DISTINCT fieldA) + MAX(CASE WHEN fieldA IS NULL THEN 1 ELSE 0 END)
like image 29
Gordon Linoff Avatar answered Oct 24 '22 04:10

Gordon Linoff