Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL - Is it possible to define the sort order?

Is it possible to define a sort order for the returned results?

I would like the sort order to be 'orange' 'apple' 'strawberry' not ascending or descending.

I know ORDER BY can do ASC or DESC but is there a DEFINED('orange', 'apple', 'strawberry') type thing?

This will be running on SQL Server 2000.

like image 486
Justin808 Avatar asked Jan 25 '11 01:01

Justin808


People also ask

How do I specify an order in SQL?

The SQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

How do I find the sort order in SQL Server?

When sorting your result set in descending order, you use the DESC attribute in your ORDER BY clause. For example: SELECT last_name FROM employees WHERE first_name = 'Sarah' ORDER BY last_name DESC; This SQL Server ORDER BY example would return all records sorted by the last_name field in descending order.


2 Answers

It's incredibly clunky, but you can use a CASE statement for ordering:

SELECT * FROM Blah  ORDER BY CASE MyColumn      WHEN 'orange' THEN 1      WHEN 'apple' THEN 2      WHEN 'strawberry' THEN 3      END  

Alternately, you can create a secondary table which contains the sort field and a sort order.

TargetValue  SortOrder orange       1 apple        2 strawberry   3 

And join your table onto this new table.

like image 76
LittleBobbyTables - Au Revoir Avatar answered Sep 29 '22 13:09

LittleBobbyTables - Au Revoir


Use a CASE statement:

ORDER BY CASE your_col            WHEN 'orange' THEN 1            WHEN 'apple' THEN 2            WHEN 'strawberry' THEN 3          END  

Alternate syntax, with an ELSE:

ORDER BY CASE             WHEN your_col = 'orange' THEN 1            WHEN your_col = 'apple' THEN 2            WHEN your_col = 'strawberry' THEN 3            ELSE 4          END  
like image 34
OMG Ponies Avatar answered Sep 29 '22 14:09

OMG Ponies