tags:

views:

70

answers:

4

Is there a way to order by column if it actually exists?

ie: SELECT * ORDER BY IF(EXISTS(order_column), order_column ASC, name_column DESC)

Thank you!

A: 

You could use ISNULL Instead

ORDER BY
    ISNULL(order_column, name_column)

Not sure how you'd add the DESC or ASC tho...

Fermin
A: 

No, EXISTS must only be used with a subquery and in the WHERE clause. May you be more specific? What do you mean by 'existing column'?

Erlock
+1  A: 

Here's my untested guess:

ORDER BY IF(ISNULL(order_column), "", order_column) ASC, name_column DESC

If order_column is NULL, an empty string will be substituted, which won't affect the sort. If it's not NULL, it will be sorted before the name column.

If Mysql won't let you use an expression in the ORDER BY, you can always create an "artificial" column in the SELECT:

SELECT 
  IF (ISNULL(order_column), "     ", order_column) 
     AS my_order_column, 
  name_column 
FROM table 
ORDER BY my_order_column ASC, name_column DESC.
Carl Smotricz
I've came up with something similar myself, but since i need to sort by order_column only if it actually exists, this won't work...
Mission
One of us is badly misunderstanding. Can you give us an example of some possible data and the result you'd expect to see?
Carl Smotricz
A: 

The best way to do this is create an expression that evaluate the if exists as part of the select query. You can have the expression return order_column or name_column

implemention depends on the SQL you are using, but here you can normallly us IIf(...) but you may need to check for null

WASSA