coder
coder

Reputation: 6233

SQL ORDER BY one of two column values with value used from first column if not null and other column if first column is null

I need an ORDER BY in my sql statement that will sort based on the value from the first column, if it's not null, and the value from the second column if the first column value is null.

It would do something like:

Select firstColumn, secondColumn 
from myTable 
order by if(firstColumn!=null) then firstColumn else secondColumn

Upvotes: 0

Views: 33

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522817

You may use COALESCE in the ORDER BY clause to implement the logic you want:

SELECT firstColumn, secondColumn
FROM myTable
ORDER BY COALESCE(firstColumn, secondColumn);

By definition, COALESCE(firstColumn, secondColumn) will return the first column if not NULL, and otherwise fall back and return the second column.

Upvotes: 3

Eray Balkanli
Eray Balkanli

Reputation: 8000

You can use case-when statement:

ORDER BY CASE 
    WHEN firstcolumn IS NOT NULL THEN firstcolumn 
    ELSE secondcolumn 
END

Upvotes: 1

Related Questions