Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: SQL Server
Expertise: Beginner
Sep 18, 1998

Sorting

Question:
I have a select query "Select * from Table where ID in (8, 2,3,78,32,1,7)" that I want returned in the same order that the IDs are in in the IN statement. By default SQL will return them sorted by the primary key (which is the ID). How can I do this?

Answer:
There is no easy way to specify your own order in the order clause. You would have to create another table with your values (8, 2,3,78,32,1,7) and their desired sequence and use that table in your select and order by. For example:

create table myorder( value int, sequence int)
insert into myorder values (8,1)
etc.. and then select ... from ... where id = myorder.value order by myorder.sequence
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date