Search code examples
sqlnullcoalesce

SQL Return Null if One Column is Null (Opposite of COALESCE())


In advance, I would like to say thanks for the help. This is a great community and I've found many programming answers here.

I have a table with multiple columns, 5 of which contain dates or null.

I would like to write an sql query that essentially coalesces the 5 columns into 1 column, with the condition that if 1 of the five columns contains a "NULL" value, the returned value is null. Essentially the opposite of the coalesce condition of returning the first non-null, I want to return the first null. If none are null, returning the greatest of the 5 dates would be optimal, however I can settle with returning any one of the 5 dates.

    C1         C2          C3        C4        C5
    --         --          --        --        --
 1/1/1991   1/1/1991    1/1/1991  1/1/1991  2/2/1992
   NULL     1/1/1991    1/1/1991  1/1/1991  1/1/1991

Query Returns:

    C1
    --
 2/2/1992
   NULL

Thank you very much.

(Server is MSSQL2008)


Solution

  • Without overthinking it:

    SELECT
      CASE WHEN c1 is null or c2 is null or c3 is null or c4 is null or c5 is null
           THEN null
           ELSE c1
      END
    FROM mytable
    

    My edit is as follows:

    CASE 
     WHEN (c1 >= c2 AND c1 >= c3) THEN c1
     WHEN (c2 >= c1 AND c2 >= c3) THEN c2
     WHEN (c3 >= c1 AND c3 >= c2) THEN c3
    END