Question: I have a table in MYSQL on which I need to perform a select and then order it by a fairly complex logic. Here is an example of my logic:

```
if(column_a is not null && column_a > 0){
   var_a = column_a
else
   var_a = 1;

if(column_a is not null){
   var_b = column_b
else
   var_b = 0

if(column_c is not null){
   var_c = column_c
else
   var_c = column_d

```

ORDER BY (var\_b\*var\_c)/var\_a

So basically, I want to do something along the lines of SELECT \* from mytable WHERE parameter = value ORDER BY variable\_to\_order\_by . I would have to use some formula for variable\_to\_order\_by, but I can't find any way of doing it which would not involve eight separate CASE WHERE statements, and that seems extremely messy. Any other suggestions?

Thanks!

Answer: 
For a down and dirty way, you can use functions in an `order by` clause. In specific, you can use the `if` and `ifnull` functions. Therefore, you should be able to do something like this:

```
SELECT ...
ORDER BY IF(some_value IS NOT NULL AND some_value RLIKE '^[[:digit:]]+$', some_value, other_value)
       - (column_baz + IF(foo > bar, a, b))/(IFNULL(yet_another_value, 0) + IF(foo > bar, a, b))

```

(where the regular expression may have to be more complex if you want to include all reals instead of just integers, if you don't want to include a string starting with 0, etc.)
a complex case/where structure is really what you need, so the mess is in the syntax. if you want to make the query more elegant, check out the [Adding New Functions to MySQL](http://dev.mysql.com/doc/refman/5.1/en/adding-functions.html) section of the reference manual. then you'll have something like this:

```
SELECT * from mytable WHERE parameter = value 
ORDER BY meaningfull_name_of_logic(
    foo, bar, some_value, other_value, yet_another_value, column_baz, a, b
);

```