Simulating MySQL's ORDER BY FIELD() in Postgresql

Viewed 35896

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?

14 Answers
SELECT * FROM (VALUES ('foo'), ('bar'), ('baz'), ('egg'), ('lol')) t1(name)
ORDER BY ARRAY_POSITION(ARRAY['foo', 'baz', 'egg', 'bar'], name)

How about this? above one fetch as below:

foo
baz
egg
bar
lol

as you already get it, if an element isn't in the array then it goes to the back.

It's also possible to do this ordering using the array unnest together WITH ORDINALITY functionality:

--- Table and data setup ...
CREATE TABLE currency_codes (
     code text null,
     name text
);
INSERT INTO currency_codes
  (code)
VALUES
  ('USD'), ('BBD'), ('GBP'), ('EUR'), ('AUD'), ('CAD'), ('AUD'), ('AUD');

-- ...and the Query
SELECT
  c.*
FROM
  currency_codes c
JOIN
  unnest('{"GBP", "EUR", "BBD", "AUD", "CAD", "USD"}'::text[])
  WITH ORDINALITY t(code, ord)
  USING (code)
ORDER BY t.ord DESC, c.name ASC;
Related