The order in column 1, if column1 is not NULL, otherwise the order in column2

Is there a way to combine ORDER BY and IS NULL in sql so that I can sort by column, if the column is not null, and if it is null, sort by another column?

+13
sql sql-order-by postgresql
source share
4 answers

Something like:

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

Same as spelling:

 ORDER BY COALESCE(Column1, Column2) 

Both should work in any sane DBMS.

+29
source share

try it

  ORDER BY COALESCE(fieldA, fieldB); 
+10
source share

You can try the following:

 ORDER BY ISNULL(firstField, secondField) 
0
source share

I don't have atm tables where I could test it, but this might work, at least without using data:

 SELECT * FROM table1 LEFT JOIN table2 ON table1.id = table2.id WHERE 1 ORDER BY IF( table2.id, table1.id, table1.name ) 

Also I don’t know what the order will look like if table2.id is sometimes null, it seems very unstable.

0
source share

All Articles