Order by Column1 value if it is not null, otherwise use Column2 value

You can use case expression:

ORDER BY CASE
    WHEN Column1 IS NOT NULL THEN Column1
    ELSE Column2
END

Or the corresponding syntactic sugar:

ORDER BY COALESCE(Column1, Column2)

The result will be like:

column1 | column2
--------|--------
      1 |    1258
      2 |    5972
   null |       3
      4 |    3698
      5 |    7524

Note that the datatype of the two columns must be comparable (the RDBMS defines the rules).

Leave a Comment

tech