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.
If this is going to be a short-lived requirement, use a case statement. However, if you think it may be around for a while, and it's always going to be
orange/apple/strawberry
order (or even if not - see below), you may want to think about sacrificing some disk space to gain some speed.Create a new column in your table called
or_ap_st
and use an insert/update trigger to populate it with the number 1, 2 or 3, depending on the the value of your fruit column. Then index on it.Since the only time the data in that column will change is when the row changes, that's the best time to do it. The cost will then be incurred on a small number of writes rather than a large number of reads, hence amortised over the
select
statements.Your query will then be a blindingly fast:
with no per-row functions killing the performance.
And, if you want other sort orders as well, well, that's why I called the column
or_ap_st
. You can add as many other sorting columns as you need.Use a CASE statement:
Alternate syntax, with an ELSE:
It's incredibly clunky, but you can use a CASE statement for ordering:
Alternately, you can create a secondary table which contains the sort field and a sort order.
And join your table onto this new table.
What I do in that case is
Not as common, but for single value operations or specific patterns, REPLACE works too
eg.
Going further from turtlepick's answer:
In case you have some more items in FRUIT and they happen to start with letters defined after THEN keywords, those items would appear within the hardcoded order. For example Banana shows up before Strawberry. You can circumvent it with
Here I have used characters with lower ASCII values in hope that they would not appear at the beginning of values in FRUIT.