Sunday, January 9, 2011

SQL order_by "field" option

Hi all,

I tried to order the SQL results in a pre-defined order. Consider the case

Am having users table, and a field called 'status' to store the current status of the user.
In back-end of my site, am displaying all the users with order-by 'status'

Possible status values are "Pending", "Approved", "Canceled", "Deleted"

I need to display users in the following orders,
"Approved", "Pending", "Canceled", "Deleted"

The normal order by field orders the field in either ASC/DESC. But in this case it is different.
For this i used the following query to fetch SQL results in a defined order

Rails finder:
User.find_by_sql("select * from users order by field (status,'Approved', 'Pending', 'Canceled', 'Deleted')")

SQL query:
select * from users order by field (status,'Approved', 'Pending', 'Canceled', 'Deleted');

Result contains the collection in the defined order.

When you are using this "order by field" option, you have to give all the option in the order then only it will works.

Thanks,
Vadivelan

1 comment: