user3159004
user3159004

Reputation:

ORDER BY with IN expression

I want to order by CustomerID but also ORDER BY 2 countries,

i have

SELECT CustomerID, Country
FROM Customer
ORDER BY Country IN ("USA", "CANADA") ASC
ORDER BY Customer ID ASC;

should return

4, Canada
7, USA
8, USA
11, USA
12, Brazil
13, Belgium

Upvotes: 0

Views: 34

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522406

Use a CASE expression in your ORDER BY clause:

SELECT CustomerID, Country
FROM Customer
ORDER BY
    CASE WHEN Country IN ("USA", "CANADA") THEN 0 ELSE 1 END,
    CustomerID;

This would put all customers in the USA or Canada first, followed by customers from all other countries. Within each of these two groups, records would be sorted ascending by the CustomerID.

Upvotes: 1

Related Questions