Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ORDER BY ... IN(...) ASC

Tags:

sql

sql-server

I want to get all profiles first that are for certain location(s):

SELECT * FROM profile
WHERE location IN ('a', 'b', 'c') OR isDefault=1 
ORDER BY location IN ('a', 'b') DESC, -- put to the front if location in 'a','b'
         isDefault DESC,              -- for each of both groups, put default profiles before the others.
         location ASC                 -- and sort each of the up to four groups by location.

This throws the error: "Incorrect syntax near the keyword 'IN'.". If I remove the order clause, results are returned.

What is wrong here?

like image 566
Alexander Avatar asked Jun 02 '15 15:06

Alexander


People also ask

Is ORDER BY DESC or ASC by default?

You can use the ASC and DESC keywords to specify ascending (smallest value first) or descending (largest value first) order. The default order is ascending.

What does the ORDER BY clause do?

An ORDER BY clause in SQL specifies that a SQL SELECT statement returns a result set with the rows being sorted by the values of one or more columns. The sort criteria do not have to be included in the result set.

What is ORDER BY and sort by?

The difference between "order by" and "sort by" is that the former guarantees total order in the output while the latter only guarantees ordering of the rows within a reducer. If there are more than one reducer, "sort by" may give partially ordered final results.

How do you use ORDER BY in case?

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. ASC or DESC is the keyword to sort the record in ascending or descending order respectively.


2 Answers

You could rewrite that to give an integer back which is sortable:

case when location IN ('a', 'b') then 0 else 1 end DESC
like image 66
Patrick Hofman Avatar answered Nov 08 '22 02:11

Patrick Hofman


You can't use IN in the ORDER BY. Change it to:

ORDER BY location ASC, --will sort a, then b, then c
like image 40
TTeeple Avatar answered Nov 08 '22 02:11

TTeeple