Search code examples
sqlsql-servercoalesce

SQL return last column value which isn't null in a set of columns


In SQL we use COALESCE to return the first value that isn't null. But how can we get the last value that isn't null in a set of columns.

eg:

COLA    COLB    COLC    COLD
Asi     Bhs     Null    Null

Expected output

Bhs


Solution

  • Do it in reverse:

    coalesce(cold, colc, colb, cola)