Using an arbitrary sort order in a SQL ORDER BY clause

Yesterday, I spent a minute helping a coworker with a SQL problem: He needed to order the results by a varchar field, but not in the easily available lexical order. The order was set by the marketing folks, and our task was to make it work.

There are three ways to do this, and I'll talk about each one.

First, you can perform the sorting after the query is done, in whatever dynamic language you are using. This is probably bad for several reasons.

Second, you could create a table that contains the values to be sorted and a field that contains the sort order in numerical fashion. This is a pain.

Third: Use a scalar function to get things to fall into place. Observe:

ORDER BY CHARINDEX(myField, 'Foo,Bar,Baz,Fizz') ASC

Quick and easy.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
Dan Novak's Gravatar FANTASTIC, thank you. I've been trying to find a simple solution for this for a few years.
# Posted By Dan Novak | 1/8/09 8:43 AM
Sam Curren's Gravatar Glad I could share. :)
# Posted By Sam Curren | 1/8/09 8:56 AM
Laker's Gravatar Is there an equivalent method is the desired "sort on" field is numeric? CHARINDEX throws an error (casting doesn't help) and PATINDEX doesn't do anything.
# Posted By Laker | 1/16/09 2:36 PM
omnibuzz's Gravatar Good one, Sam. Just a small suggestion if I may
Would you agree using this rather than what you suggested to avoid a
potential problem.

ORDER BY CHARINDEX(','+ myField + ',' , ',Fool,Foo,Bar,Baz,Fizzy,Fizz,') ASC
# Posted By omnibuzz | 11/17/09 10:05 AM
# Posted By supra shoes | 5/14/10 5:54 AM
# Posted By coach handbags | 5/17/10 1:42 AM
# Posted By gucci bags | 5/22/10 8:28 AM
# Posted By chanel bags | 5/29/10 12:27 AM