By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,378 Members | 1,407 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,378 IT Pros & Developers. It's quick & easy.

need same order as the IN list of ids ...

P: 1
Hi,

I have this Query : SELECT field_name FRM meta WHERE id IN ('13','11','7','8','9','10','12')

I want the rows to be display in the same order as the IN list
of ids.Any ideas?

All the best wished,
Regards and Thanks,
Pong
Apr 2 '08 #1
Share this Question
Share on Google+
2 Replies


ck9663
Expert 2.5K+
P: 2,878
Hi,

I have this Query : SELECT field_name FRM meta WHERE id IN ('13','11','7','8','9','10','12')

I want the rows to be display in the same order as the IN list
of ids.Any ideas?

All the best wished,
Regards and Thanks,
Pong
Will this work?
Expand|Select|Wrap|Line Numbers
  1. SELECT 
  2. field_name FRM meta WHERE id IN ('13','11','7','8','9','10','12')
  3. order by case 
  4. when id = 13 then 1
  5. when id = 11 then 2
  6. else id
  7. end
  8.  
if not put in a subquery

Expand|Select|Wrap|Line Numbers
  1. (SELECT top 100 PERCENT
  2. sortid = case 
  3. when id = 13 then 1
  4. when id = 11 then 2
  5. else id
  6. end,
  7. field_name FRM meta WHERE id IN ('13','11','7','8','9','10','12'))
  8. order by sortid
  9.  
try the first one first. it's faster

--CK
Apr 2 '08 #2

Brad Orders
P: 21
You could also consider putting the values inside the "IN" statement in their own table. Then you could solve the problem by doing a simple join, and order by the identity ID in the new table.

If performance is important, this is a solution worth considering.
Apr 4 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.