Programming Without Walls
Software Engineering with Microsoft .net

Dynamic Sort Parameters in MS SQL Server 2005

April 29, 2008 by Bob Barth

I prefer to have the parts of a software system that are good at particular tasks to do those tasks. Case in point: sorting. SQL Server (with proper indexes) is very good at sorting data, so I make sure that most, if not all of the sorting of data in my applications occurs in stored procedures in SQL Server.

This can cause a bit of a problem, however, if you're developing an application that permits the user to sort by different columns. One solution would be to write as many different stored procedures as you have sort criteria. Maintenance would be a nightmare on that so I don't think it's a good idea. Another way would be to parameterize the sort criteria into either a string or magic numbers and use a case statement in the ORDER BY clause to figure out what to sort by. That is the method I often use, and it looks like this:

   1: order by
   2:     case 
   3:     when @sortExpression = 'lastname asc' then CAST(LastName as sql_variant)
   4:     when @sortExpression = 'firstname asc' then CAST(FirstName as sql_variant)
   5:     end asc,
   6:     case
   7:     when @sortExpression = 'lastname desc' then CAST(LastName as sql_variant)
   8:     when @sortExpression = 'firstname desc' then CAST(FirstName as sql_variant)
   9:     end desc

In this example, imagine we are sorting a table with a person's first and last names as fields named (conveniently) FirstName and LastName. The first part permits sorting in ascending order and the second part permits sorting in descending order. The @sortExpression takes the form that .net data controls serve up. It is important to CAST the field names as sql_variant type. In this example, it doesn't really matter, however, if the data types of the columns that are returned from the case statement are different (e.g. an NVARCHAR and a DATETIME), SQL Server will complain because it can't figure out what data type you're trying to return (it will choose the data type of the first element in the CASE statement, and anything that isn't that type or can be implicitly converted to that type, will cause it to have an error at run-time).

Okay, so this solves the immediate problem of being able to sort by parameter, but what if we want to sort by multiple fields? For example, when the user sorts by LastName (as in the example above), shouldn't the software also sort by FirstName as a secondary sort field? Of course it should. Here's how you do that:

   1: order by
   2:     case 
   3:     when @sortExpression = 'lastname asc' then CAST(LastName as sql_variant)
   4:     when @sortExpression = 'firstname asc' then CAST(FirstName as sql_variant)
   5:     end asc,
   6:     case when @sortExpression = 'lastname asc' then CAST(FirstName as sql_variant) end asc,
   7:     case when @sortExpression = 'firstname asc' then CAST(LastName) as sql_variant) end asc,
   8:     case
   9:     when @sortExpression = 'lastname desc' then CAST(LastName as sql_variant)
  10:     when @sortExpression = 'firstname desc' then CAST(FirstName as sql_variant)
  11:     end desc,
  12:     case when @sortExpression = 'lastname desc' then CAST(FirstName as sql_variant) end desc,
  13:     case when @sortExpression = 'firstname desc' then CAST(LastName as sql_variant) end desc

Notice lines 6, 7, 12, and 13. These lines inject another field into the order by clause after the first case statement has already returned the primary field. They are whole CASE statements all on their own. You can continue to add fields to the sort list in this way until your hands get tired. In this example, I'm sorting by FirstName as a secondary field when the user selects the LastName field to sort by (and vice-versa); you, however, can make it do whatever you want. For example, you might permit the user to sort by HireDTm (representing the date this person was hired), and then by LastName and FirstName using the technique above. If you happen to also need the ability to page the returned data, this method also works perfectly with the ROW_NUMBER() OVER() syntax also introduced in SQL Server 2005. Just put the order by information in the OVER() part.

Of course, nothing is perfect and there are a couple of problems with this method. The first (which I consider minor) is that the user cannot select the secondary (and further) sort fields. I suppose if you really wanted to, you could change the @sortExpression parameter to be something other than what I have above and instead pass in a value that indicates which of a matrix of combinations of sort fields the user has selected, and then write the WHEN parts of the CASE statement for every combination the user could choose. While that would probably work, I'm thinking it's overkill (and a lot of work). You can usually get away with a couple of static secondary field choices, as long as you spend a couple of moments thinking about how the data is used by the user.

The second problem is that this method is not very speedy. In a table with 500,000 rows, it will return in about two seconds (my test table had six columns, one primary key integer IDENTITY column, and five data columns, which were NVARCHAR(50), NVARCHAR(100), INT, INT, and NUMERIC(14, 4)). In a table with over three million rows (3.2 to be exact), it took between 18 and 22 seconds. I didn't do enough tests to see if the speed degradation is linear or geometric, but it's not good, nonetheless. If you use this method, use it on smallish tables.

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Related posts

Comments

October 30, 2009 7:57 AM

fast cash loans

thanks! very helpful post!! like the template btw ;)

fast cash loans

November 14, 2009 3:00 AM

pay day loans

Searching for this for some time now - i guess luck is more advanced than search engines Smile

pay day loans

November 26, 2009 1:04 PM

Andrew Pelt

One of my favorite gmaes, thank you! You can find loads of games like this over at http://www.realarcader.com

Andrew Pelt

November 27, 2009 1:00 PM

eve beginner guide

Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon.

eve beginner guide

November 27, 2009 8:36 PM

Search engine placement specialist

I admit, I have not been on this webpage in a long time... however it was another joy to see It is such an important topic and ignored by so many, even professionals. I thank you to help making people more aware of possible issues.

Search engine placement specialist

December 3, 2009 12:39 AM

Låna pengar

Thanks for writing your thoughts. Thanks again, Daisy Barlow @ lanapengar

Låna pengar

December 3, 2009 2:33 PM

Orlando Cieslak

An intriguing article. Given the current economic conditions which do seem to be bettering it is positive to see that there are movements within the financial services sphere. This is attested within the wider availability of credit for individual customers and businesses. The diverse wordwide stimulus packages have all facilitated this but we continue to have some way to go.

Orlando Cieslak

December 4, 2009 8:23 PM

Search engine placement specialist

The blog was absolutely fantastic! Lots of great information and inspiration, both of which we all need!

Search engine placement specialist

December 4, 2009 8:38 PM

Kevin Stacey

Intimately, the article is actually the freshest on this precious topic. I concur with your conclusions and will eagerly look forward to your incoming updates. Just saying thanks will not just be enough, for the exceptional lucidity in your writing. I will immediately grab your rss feed to stay abreast of any updates. Fabulous work and much success in your business enterprize!

Kevin Stacey

December 5, 2009 1:11 AM

reverse mortgage az,phoenix mortgage in reverse

I REALLY liked your post and blog! It took me a little bit to find your site...but I book marked it. Would you mind if I but a link back to your site?

reverse mortgage az,phoenix mortgage in reverse

December 6, 2009 2:17 AM

mahjong games

hello blogger, I found your blog from yahoo and read a few of your other posts.They are incredible. Please keep it up!!! take care, Samantha.

mahjong games

December 8, 2009 10:24 PM

decorative window film

thanks for the useful tips here. I've got a home improvement blog that I work extremely hard on like you are doing here. My efforts skew towards a lot of general topics and hopefully provide high level answers for what people are looking for. Keep on doing a nice job with your site

decorative window film

December 10, 2009 5:09 AM

faxless payday loans

I guess there's always an easier way ...

faxless payday loans

December 10, 2009 1:59 PM

personalized gift

The blog post was right on. It was an easy read. Bye, Alma Holoff @ tinypocketpeple

personalized gift

December 10, 2009 5:55 PM

Panasonic Lumix

Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with more information? It is extremely helpful for me.

Panasonic Lumix

December 11, 2009 9:51 AM

Scott Hancock

I just wanted to thank you very much for this ensightful article. I have already bookmarked your site, when I have more free time I am going to have to do some further reading. Well back to my dreaming of Panama (see what I mean at this Harvard website http://blogs.law.harvard.edu/panama/panama) or back to the books - I wonder which one is going to win out. Smile

Scott Hancock

December 11, 2009 12:43 PM

lånar pengar

You got a really useful blog. Thank you for sharing your views on this. Keep up the good work, Aidan Kaplan @ lanapenar

lånar pengar

December 11, 2009 1:21 PM

Canon Ixus

This is such a great resource that you are providing and you give it away for free. I enjoy seeing websites that understand the value of providing a prime resource for free. I truly loved reading your post. Thanks!

Canon Ixus

December 11, 2009 4:08 PM

حلقات حياتي

Hola Smile First Sorry if I used an arabic name Because it is already used from the first time in all English and non English sites and Considerably, the post is in reality the best on this deserving topic. I harmonize with your conclusions and will thirstily look forward to your approaching updates. Just saying thanks will not just be enough, for the exceptional clarity in your writing. I will at once grab your rss feed to stay privy of any updates. Pleasant work and much success in your business efforts!

حلقات حياتي

December 11, 2009 4:54 PM

TELFER

Very interesting post - it was new to me. Thanks.

TELFER

December 11, 2009 11:15 PM

best acai berry product

Greetings to all, This site is high-quality and so is the manner in which the issue was developped. I like some of the comments too even though I would rather we don't err from the main point in order add value to the topic. It will be also encouraging to the person who wrote it if we all could pass it around (for some of us who use social media such as a digg, facebook,..). Again, Thanks..

best acai berry product

December 12, 2009 1:18 PM

Watch Free Movies

Gibraltar's Kaiane Aldorino claimed the title of Miss World 2009 on Saturday, defeating 111 other hopefuls at a glittering ceremony in South Africa. Mexico's Perla Beltran came second, with South African entry Tatum Keshwar taking third place. - Missy

Watch Free Movies

December 12, 2009 1:58 PM

The Saxon Chronicles

Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon.

The Saxon Chronicles

December 13, 2009 5:47 PM

Early Learning

I know this is really boring and you are skipping to the next comment, but I just wanted to throw you a big thanks - you cleared up some things for me!

Early Learning

December 14, 2009 8:49 AM

Roxie Whitehurst

An motivating and absorbing article thanks. Getting out of your liabilities is a tough thing to do and I must know. I have been in money owing situation for nearly four years and have only now started to claw my method out of it using a credit counselling service. I highly recommend them as they will help you speak using your creditors and negotiate your debt down to a managable level. Well worth the effort but specifically make certain you go with a respectable organisation.

Roxie Whitehurst

December 14, 2009 5:26 PM

The Lion King

It appears that you have placed a lot of effort into your article and I require more of these on the net these days. I sincerely got a kick out of your post. I don't really have much to say in response, I only wanted to comment to reply wonderful work.

The Lion King

December 14, 2009 11:39 PM

Peridot Earrings  The green shine

Intimately, the post is actually the sweetest on this worthw hile topic. I harmonise with your conclusions and will eagerly look forward to your incoming updates. Saying thanks will not just be enough, for the extraordinary clarity in your writing. I will right away grab your rss feed to stay informed of any updates. Solid work and much success in your business dealings!

Peridot Earrings The green shine

December 15, 2009 5:52 PM

se doigter

I'll gear this review to 2 types of people: current Zune owners who are considering an upgrade, and people trying to decide between a Zune and an iPod. (There are other players worth considering out there, like the Sony Walkman X, but I hope this gives you enough info to make an informed decision of the Zune vs players other than the iPod line as well.)

se doigter

December 15, 2009 8:13 PM

Children's toys

Aw, this was a really quality post. In theory I'd like to write like this too - taking time and real effort to make a good article... but what can I say... I procrastinate alot and never seem to get something done.

Children's toys

December 15, 2009 10:38 PM

jeux casino

Great work thanks for sharing

jeux casino

December 16, 2009 1:48 AM

youdoodoll

I stumbled upon your blog by chance. Very informative post. Eric Bradfield @ youdodoll

youdoodoll

December 16, 2009 8:30 AM

Gloria - Back Pain Relief

<p>I am an average mid 40-ties working mom from Southeast California, and as a hobby, I run marathons. Hence, I have to deal with lower back pain oftentimes. After I did run my last run I had to stop for a while. It was hurting awfully. Meanwhile I have thankfully made a return to running. I followed the advice I found here: <a href="www.info-backpain.com/.../" target="_blank">Get Back Pain Relief Now</a></p><p>Many thanks again and keep up your authentic work and much success in your business efforts!</p><p>I wish you all a Merry Christmas and a Happy New Year!</p><p>Give A Helping Hand

Have you ever heard of <a href="http://www.grameenfoundation.org" target="_blank">grameenfoundation.org yet? Grameen Foundation - Escape poverty through access to microfinance and technology</a>.</p>

Gloria - Back Pain Relief

December 16, 2009 6:29 PM

ELC

Aw, this was a really quality post. In theory I'd like to write like this too - taking time and real effort to make a good article... but what can I say... I procrastinate alot and never seem to get something done.

ELC

December 16, 2009 11:04 PM

aoc gold guide

That is some inspirational stuff. Never knew that opinions could be this varied. Thanks for all the enthusiasm to offer such helpful information here.

aoc gold guide

December 17, 2009 12:45 PM

nigeria holidays

First Of All, let me commend your clarity on this subject. I am not an expert on this subject, but after studying your article, my understanding has developed considerably. Please permit me to snap up your rss feed to remain in touch with any potential updates. Solid job and will offer it on to admirers and my fans.

nigeria holidays

December 17, 2009 2:29 PM

start bet

Generally I do not post on sites, but I would like to say that this post really convinced me to do so! Thanks, very good site.

start bet

December 17, 2009 9:09 PM

Michael

Hello, I run across this website by on accident when I was looking on Google then I popped in to your site. I must tell you that your web site is very cool I like your theme! I don't have much free time at the current moment to go through your sitebut I have bookmarked it. I will come back in a day or two. Thanks for a great site.

Michael

December 18, 2009 2:34 AM

start bet

Usually I do not post on sites, but I would like to say that this site really forced me to do it! Thanks, very good site.

start bet

December 18, 2009 5:09 AM

Phantom Of The Opera

We just couldnt leave your website before saying that we really enjoyed the quality information you offer to your visitors... Will be back often to check up on new stuff you post!

Phantom Of The Opera

December 18, 2009 10:19 AM

Cindy

How are you, I arrived at this site by accident when I was looking on Google then I came upon your web site. I have to say your web site is cool I really like your theme! At this moment I don’t have much free-time at the moment to read your sitebut I bookmarked it. I will come back in a day or two. Thanks for a great site.

Cindy

December 18, 2009 11:10 AM

Certificate of Deposit

The funding, from the federal stimulus package, was confirmed by the U.S. Department of Agriculture's Rural Utility Service, TDS said.

Certificate of Deposit

December 18, 2009 11:59 AM

Golf Club Sets   Useful Shopping Tips For Golfers

Intimately, the post is actually the sweetest on this worthw hile topic. I harmonise with your conclusions and will eagerly look forward to your incoming updates. Saying thanks will not just be enough, for the extraordinary clarity in your writing. I will right away grab your rss feed to stay informed of any updates. Solid work and much success in your business dealings!

Golf Club Sets Useful Shopping Tips For Golfers

December 18, 2009 2:06 PM

gilbert arizona realtor

I frequently don't leave comments!!! Trust me! Yet I liked your blog...especially this post! Would you mind terribly if I put up a backlink from my site to your site?

gilbert arizona realtor

December 18, 2009 3:12 PM

Football

I know this is really boring and you are skipping to the next comment, but I just wanted to throw you a big thanks - you cleared up some things for me!

Football

December 18, 2009 5:02 PM

listing home

Dude... good post! I might actually even listen to what you are saying. Overall your whole blog is tremendous... I am digging it. Peace!

listing home

December 18, 2009 6:13 PM

Cindy

I visit your web site once in a while and I must say that I like your template!

Cindy

December 19, 2009 2:33 AM

Craps guide

<P>Thanks for this post, what a great site and good posts, I will bookmark this post. Regards </P>

Craps guide

December 19, 2009 4:49 AM

natalie cahew

essential post , really good position on the subject and very well written, this certainly has put a spin on my day, umpteen thanks from the USA and keep up the good work

natalie cahew

December 19, 2009 2:02 PM

Scott

Howdy, I encountered this website by accident when I was searching on Google then I went on your web site. I must say your website is really cool I really like your theme! Right now I don’t possess much time at the moment to go through your sitebut I have bookmarked it. I will come back in a day or two. Thanks for a great site.

Scott

December 19, 2009 2:15 PM

Sandra

Nice to see you posting on this topic, I have to bookmark this website. Just keep up the good work.

Sandra

December 19, 2009 2:31 PM

CD Rates

Those who lament the scant rates on their savings may want to review where they stand. Here is a quick look at low-risk options and some of the pluses and minuses of stashing your cash in each:

CD Rates

December 19, 2009 3:28 PM

Ice Hockey

This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here! keep up the good work.

Ice Hockey

December 19, 2009 7:24 PM

Blogs Blog

very informative thank you for a nice site

Blogs Blog

December 19, 2009 9:47 PM

regcure

<P>this really helps, today i receive the problems and i donot know how to puzzle out,
i research google and found your blog,
thanks once more</P><P>one thing, can i post this article on my site? i will add the source.</P><P>regards!</P>

regcure

December 20, 2009 12:33 AM

James Romero

I stumbled upon this page while surfing and I can say it's worth the time I spent on it. Keep it up! You can be sure that I'll be back for more.

James Romero

December 20, 2009 2:19 AM

Meilleurs casinos

<P>Thanks for this post, this is a good post and good blog, I will keep in mind this blog. Regards </P>

Meilleurs casinos

December 20, 2009 5:39 AM

Download music

I just couldnt leave your website before saying that I really enjoyed the quality information you offer to your visitors... Will be back often to check up on new stuff you post!

Download music

December 20, 2009 8:30 AM

designer bags sale

Comfortabl y, the article is in reality the best on this valuable topic. I harmonise with your conclusions and will thirstily look forward to your coming updates. Just saying thanks will not just be sufficient, for the wonderful clarity in your writing. I will instantly grab your rss feed to stay privy of any updates. Fabulous work and much success in your business dealings!

designer bags sale

December 20, 2009 11:20 AM

CD Rates

Cool post! How much stuff did you have to look up in order to write this one? I can tell you put some work in.

CD Rates

December 20, 2009 4:22 PM

Michael

That is nice to definitely locate a web site where the blogger knows really well about his subject.

Michael

December 20, 2009 5:22 PM

Brynn Teasley

I heard there is a new solitaire game. My close friend made me try it, and I really think it's the best solitaire game ever made! I got it here: <a href="http://www.funsolitairegame.com/">Get" rel="nofollow">http://www.funsolitairegame.com/">Get The Solitaire Game</a> http://www.funsolitairegame.com/

Brynn Teasley

December 20, 2009 5:52 PM

Spencer

Most of the time I do not make comments on blogs, but I want to say that this post really forced me to do so. Really nice post!

Spencer