Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using +0 in order clause

Tags:

sql

mysql

I have a column "available" which either returns "yes" or for instance "30 min". To sort this table we have found out that this works as intended where "Yes" comes first, and the "30 min" comes after.
order by available + 0 asc
Even though this works we do not know why we have to put +0 to the column. Can someone elaborate?

Edit: This is an example on a query
Note that all where clauses are not here, and the if(x is null) is to return something if there is no result aka null value.

select distinct r.rname, if(b.stime is null, 'Yes', 'Yes') as available, r.mperson
from Rooms r left outer join Bookings b using (rname)
union all
select b.rname, concat(minute(timediff(b.etime, '$sdate')), ' min') as available,      r.mperson
from     Bookings b inner join Rooms r using(rname)
order by    available + 0 asc, rname asc
like image 533
Richard Avatar asked Oct 20 '25 21:10

Richard


1 Answers

You're implicitely converting the available value to a number, as you can see by trying

select "30 minutes" + 0; ==> returns 30
select "2 hours" + 0; ==> returns 2
select "yes" + 0; ==> returns 0

This makes "yes" (or any string not starting by a number) the first returned value instead of the last one.

This does change the order but this feels hacky and is less efficient than using a pure numeric field (which could be indexed).

More generally you always should define your schema such as to have precise non polymorphic fields.

like image 73
Denys Séguret Avatar answered Oct 22 '25 12:10

Denys Séguret