Search code examples
sqlnulldistinct-values

SQL eleminate mulitple value(s) if same identifier has a associated NULL value


Ok here goes:

I have a table with id ( can be duplicate but not NULL ) and value ( can be duplicate and NULL )

id      value
-----   -----
1       red
1       red
1       (null)
2       blue
2       blue
3       (null)

So how do I return the id's and value's of all the records that have a value, but if a null value is also found don't include it in the result set.

So the return would be

id      value
-----   -----
2       blue

as id 1 and 3 have a value of (null) in one or more of the results


Solution

  • It's a typical "select where not exists"-type query with many ways to write the answer, for example:

    Using a LEFT JOIN / WHERE ... IS NULL:

    SELECT DISTINCT T1.id, T1.value
    FROM your_table T1
    LEFT JOIN your_table T2
    ON T1.id = T2.id AND T2.value IS NULL
    WHERE T2.id IS NULL
    

    Using NOT IN:

    SELECT DISTINCT id, value
    FROM your_table
    WHERE id NOT IN
    (
        SELECT DISTINCT id
        FROM your_table
        WHERE value IS NULL
    )
    

    Using NOT EXISTS:

    SELECT DISTINCT id, value
    FROM your_table
    WHERE NOT EXISTS
    (
        SELECT NULL
        FROM your_table T1
        WHERE your_table.id = T1.id AND T1.value IS NULL
    )