Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order By Last in SQL: Force a value to be last in the order

In SQL, I have used

...ORDER BY name DESC NULLS LAST

which works quite awesome, yet is there any way that I can set a specific value to be last? Such as an empty string (@EMPTY).

...ORDER BY name DESC (@EMPTY) LAST

I am dynamically building SQL off of user choices on a table, and when the user changes the sort order, I change my sort order in my SQL. Also, the user can choose which column to sort by. The column that I am sorting by will either be type text or type int. I don't need any fancy ORDER BY when column is type int, but I do need to force all values of "" to the end of the ORDER BY when the type of the column is text.

Thanks!

like image 426
WebWanderer Avatar asked Feb 10 '23 17:02

WebWanderer


1 Answers

You can use a case as the first element in the sort order:

order by
    case when name = '' then 1 else 0 end
,   name desc
like image 50
Andomar Avatar answered Feb 13 '23 07:02

Andomar