Reputation: 6233
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
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
Reputation: 8000
You can use case-when
statement:
ORDER BY CASE
WHEN firstcolumn IS NOT NULL THEN firstcolumn
ELSE secondcolumn
END
Upvotes: 1