Getting and ordering rows with value greater than zero then rows with value zero Getting and ordering rows with value greater than zero then rows with value zero sql sql

Getting and ordering rows with value greater than zero then rows with value zero


SELECT *FROM atableORDER BY  display_order = 0,  display_order

When display_order is 0, the first sorting term, display_order = 0, evaluates to True, otherwise it evaluates to False. True sorts after False – so, the first sorting criterion makes sure that rows with the display_order of 0 are sorted at the end of the list.

The second ORDER BY term, display_order, additionally specifies the order for rows with the non-zero order values.

Thus, the two criteria give you the desired sorting order.


Try the below one-

SELECT * FROM table_name ORDER BY IF (display_order = 0, 9999999, display_order)


Here is the solution in T-SQL in case anyone needs it

SELECT * FROM Table ORDER BY CASE WHEN display_order = 0 THEN display_order END ASC,CASE WHEN display_order > 0 THEN display_order  END ASC