Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server - Order by case

Tags:

sql

sql-server

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

  • Berlin
  • Algeria
  • Australia
  • Fiji
  • Greece
  • ...

Hope that makes sense,

I currently have the following...

SELECT CompanyName, City
FROM customers
ORDER BY case when City = 'Berlin' END
like image 207
Tom Avatar asked Sep 08 '10 10:09

Tom


People also ask

Can you ORDER BY case in SQL?

Although it is most often used there, CASE is not limited to SELECT statements. For example, you can use it in clauses like IN , WHERE , HAVING , and ORDER BY . Using a CASE statement in a query once doesn't mean you have hit your quota for using it. You can use it multiple times in a single query.

How do you use ORDER BY in case statement?

CASE Syntax: CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 WHEN condition3 THEN result3 ELSE result END; ORDER BY: This keyword is used to sort the result-set in ascending or descending order. It sorts the records in ascending order by default.

Can I use CASE statement in ORDER BY clause?

We can use Case statement with order by clause as well. In SQL, we use Order By clause to sort results in ascending or descending order. Suppose in a further example; we want to sort result in the following method. We can define this condition with a combination of Order by and Case statement.

Is SQL ORDER BY case sensitive?

SQL Server is, by default, case insensitive; however, it is possible to create a case-sensitive SQL Server database and even to make specific table columns case sensitive.


1 Answers

Almost:

SELECT CompanyName, City
FROM customers
ORDER BY CASE WHEN City = 'Berlin' THEN 0 ELSE 1 END, City
like image 90
tdammers Avatar answered Sep 22 '22 14:09

tdammers