Simon Callan
Simon Callan

Reputation: 3130

Ordering SQL SELECT by result of a string comparison

I have a table with two string columns, ID and LANGUAGE. Language can be one of CYM, ENG, GAE.

When selecting data from the table, I want to order it by the language column, putting a specified language at the start of the results, with the other languages later, in any order.

Say I have the data

+===+=====+
+ 1 + CYM +
+ 2 + GAE +
+ 3 + ENG +
+ 4 + CYM +
+===+=====+

and I want the output to be

+===+=====+
+ 3 + ENG +
+ 1 + CYM +
+ 2 + GAE +
+ 4 + CYM +
+===+=====+

How do I do the equivalent of

SELECT ID, LANGUAGE 
FROM TABLE 
ORDER BY (LANGUAGE = 'ENG'), ID

Upvotes: 1

Views: 42

Answers (1)

Lukasz Szozda
Lukasz Szozda

Reputation: 175726

You can use CASE WHEN to ensure ENG will be first:

SELECT ID, LANGUAGE
FROM your_table
ORDER BY 
  CASE LANGUAGE WHEN 'ENG' THEN 0
                ELSE 1
  END ASC;
  -- ,ID ASC -- if needed

LiveDemo

Upvotes: 3

Related Questions