Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order by Column1 if Column1 is not null, otherwise order by Column2

Tags:

Is there a way to combine ORDER BY and IS NULL in sql so that I can order by a column if the column isn't null, but if it is null, order by another column?

like image 656
1252748 Avatar asked Jun 12 '12 19:06

1252748


2 Answers

Something like:

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

Same as writing:

ORDER BY COALESCE(Column1, Column2) 

Both should work in any sane RDBMS.

like image 164
Salman A Avatar answered Jan 01 '23 19:01

Salman A


Try this

  ORDER BY COALESCE(fieldA, fieldB); 
like image 26
vearutop Avatar answered Jan 01 '23 19:01

vearutop