Tom
Tom

Reputation: 71

SQL Server - Order by case

I am trying to get the following query to display the results in alphabetical order by City except for the fact that I want "Berlin" to appear at the top of the list

So the results would look something like

Hope that makes sense,

I currently have the following...

SELECT CompanyName, City
FROM customers
ORDER BY case when City = 'Berlin' END

Upvotes: 6

Views: 22316

Answers (6)

Ralf de Kleine
Ralf de Kleine

Reputation: 11734

SELECT CompanyName, City, CASE WHEN City = 'Berlin' THEN 0 ELSE 1 END AS Ordering
FROM customers
ORDER BY Ordering, City

Upvotes: 7

SPIRiT_1984
SPIRiT_1984

Reputation: 2767

How about using Union? Something like this, for example:

SELECT 1 as Weight, CompanyName, City FROM customers
WHERE city='Berlin'
UNION ALL
SELECT 2 as Weight, CompanyName, City FROM
customers 
WHERE city<>'Berlin'
ORDER BY Weight, City

Upvotes: 0

badbod99
badbod99

Reputation: 7526

As blank string appears first in any string ordered list, all other results sorted normally. So this works perfectly:

SELECT CompanyName, City
FROM customers
ORDER BY CASE WHEN City = 'Berlin' THEN '' ELSE City END

Tested with:

CREATE TABLE customers (CompanyName VARCHAR(50), City VARCHAR(50))

INSERT INTO customers VALUES ('Customer1', 'Berlin')
INSERT INTO customers VALUES ('Customer2', 'Algeria')
INSERT INTO customers VALUES ('Customer3', 'Australia')
INSERT INTO customers VALUES ('Customer4', 'Fiji')
INSERT INTO customers VALUES ('Customer5', 'Greece')

SELECT CompanyName, City
FROM customers
ORDER BY CASE WHEN City = 'Berlin' THEN '' ELSE City END

-- OUPUT
-- Customer1    Berlin
-- Customer2    Algeria
-- Customer3    Australia
-- Customer4    Fiji
-- Customer5    Greece

Upvotes: 1

Adriaan Stander
Adriaan Stander

Reputation: 166326

Try something like

SELECT CompanyName, City 
FROM customers 
ORDER BY case when City = 'Berlin' THEN 0 ELSE 1 END, City

Upvotes: 2

tdammers
tdammers

Reputation: 20721

Almost:

SELECT CompanyName, City
FROM customers
ORDER BY CASE WHEN City = 'Berlin' THEN 0 ELSE 1 END, City

Upvotes: 16

Kirill Leontev
Kirill Leontev

Reputation: 10931

SELECT CompanyName, City 
FROM customers 
ORDER BY case when City = 'Berlin' then 1 else 999 END asc

Upvotes: 1

Related Questions