Rather than SELECT all columns, name those you want/need. And one of them can be a named expression that does the calculation for you. You may then use that in your ORDER BY clause. You can use the IF syntax in the expression, or CASE perhaps. Control Flow Functions [dev.mysql.com] are going to come in handy.