SQL: using clause with "ORDER BY"

48 views Asked by At

I have a list of orders in a SQL table, and for each order I have a ship-to country code.

example:

order     country_code
X00145    GB
X00178    FR
D55454    AL
E54566    GB
F59565    IE
O84849    ES
K54545    US
N61465    GB
W65478    GB

I am trying to sort the output so orders that are not going to country_code GB are returned first, alphabetically , and then have the GB orders come last (like after IE and US in my example above).

Using "ORDER BY" only lets me filter with ASC or DESC. Is there a way to use a clause along with "ORDER BY"? (I guess not because I could not find anything online)?

3

There are 3 answers

0
Abhik Chakraborty On

You can use order by field()

select * from table_name
order by field(country_code,'GB') desc,country_code

DEMO

0
juergen d On

For MySQL you could do

select * from your_table
order by country_code = 'GB', 
         country_code,
         `order`

or generally

select * from your_table
order by case when country_code <> 'GB' then 1 else 2 end, 
         country_code,
         `order`
0
Ronak Shah On

try this:

select * from yourtable where  country_code != 'GB' order by country_code

Union 

select * from yourtable where  country_code = 'GB'