Just trying out PostgreSQL for the first time, coming from MySQL. In our Rails application we have a couple of locations with SQL like so:
SELECT * FROM `currency_codes` ORDER BY FIELD(code, 'GBP', 'EUR', 'BBD', 'AUD', 'CAD', 'USD') DESC, name ASC
It didn't take long to discover that this is not supported/allowed in PostgreSQL.
Does anyone know how to simulate this behaviour in PostgreSQL or do we have to pull sorting out into the code?
Create a migration with this function
Then just do this
voila!
If you'll run this often, add a new column and a pre-insert/update trigger. Then you set the value in the new column based on this trigger and order by this field. You can even add an index on this field.
Actually the version for postgres 8.1 as another advantage.
When calling a postgres function you cannot pass more than 100 parameters to it, so your ordering can be done at maximum on 99 elements.
Using the function using an array as second argument instead of having a variadic argument just remove this limit.
As I answered here, I just released a gem (order_as_specified) that allows you to do native SQL ordering like this:
It returns an ActiveRecord relation, and thus can be chained with other methods, and it's worked with every RDBMS I've tested.
You can do this...
But why are you hardcoding these into the query -- wouldn't a supporting table be more appropriate?
--
Edit: flipped it around as per comments
sort in mysql:
in postgres: