Solved

Preserve return order WHERE IN

Posted on 2009-06-29
5
304 Views
Last Modified: 2012-05-07
I am running a SQL query like below, where the list could be any number of ID values in any order. I would like the query to return the values in the exact order they are fed in, not ascending or descending by any column. SQL seems to default to ordering them ascending by the ID - I am looking to override this behavior.

i.e. as written below, I want the returned rows to be ordered:
3106 blah blah
3104 blah blah
3109 blah blah

Is there a way to do thie?
SELECT * 

FROM products

WHERE product_id IN (3106, 3104,3109)

Open in new window

0
Comment
Question by:sailing_12
  • 3
5 Comments
 
LVL 40

Expert Comment

by:mrjoltcola
ID: 24741245
SQL will not order them, the physical storage layer will order them according to either the random block location or an ordered index.

You cannot rely on a specific ordering unless you explicitly specify an order in your SELECT.

If you want to guarantee ordering based on the order of insert, add a TIMESTAMP or AUTOINCREMENT field and order by that.
0
 
LVL 40

Expert Comment

by:mrjoltcola
ID: 24741250
>>SQL will not order them

I did not state that well...

I meant, SQL will not order them unless you specify an ORDER BY. Otherwise, it will just take them as they are retrieved. It is the low level database engine that orders them. Without an ORDER BY then ordering is a side effect of the physical storage layer but cannot be relied upon and can change. Always use an order by if you want ordering.


0
 
LVL 40

Accepted Solution

by:
mrjoltcola earned 150 total points
ID: 24741265
Sorry for the triple posting, I normally avoid that.

If you have a short list of ids that you want to order by in the IN() clause you can add an explicit ORDER BY CASE statement. See below.

But if you want this to work in general purpose, you're code generator will need to dynamically generate the ORDER BY (CASE ..) to match your IN() clause.



SELECT * 

FROM products

WHERE product_id IN (3106, 3104,3109)

ORDER BY (case when id = 3106 then 1 when id = 3104 then 2 when id = 3109 then 3 end);

Open in new window

0
 
LVL 75

Assisted Solution

by:Aneesh Retnakaran
Aneesh Retnakaran earned 150 total points
ID: 24741310
Assuming you are passing a CSV like this '3106, 3104,3109'


create function dbo.fn_ParseString
(
@String       varchar(8000) ,
@Delimiter      varchar(10)
)
returns @tbl table (i int, s int )
as
begin
declare @i int, @j int

      select       @i = 1
      while @i <= len(@String)
      begin
            select      @j = charindex(@Delimiter, @String, @i)
            if @j = 0
            begin
                  select      @j = len(@String) + 1
            end
            insert      @tbl select LTRIM( RTRIM( substring(@String, @i, @j - @i) ) )
            select      @i = @j + len(@Delimiter)
      end
      return
end

go


SELECT *  
FROM products p
inner join dbo.fn_ParseString ('3106,3104,3109' ) t
ON p.Product_ID =  t.s
ORDER BY t.i
0
 

Author Closing Comment

by:sailing_12
ID: 31598177
Based on your answers, I re-worked my webserver-side code to loop separate queries for each ID in the order they are input into a form.

I found this preferable to the solutions suggested, but thanks for giving me a direction.
0

Featured Post

Get up to 2TB FREE CLOUD per backup license!

An exclusive Black Friday offer just for Expert Exchange audience! Buy any of our top-rated backup solutions & get up to 2TB free cloud per system! Perform local & cloud backup in the same step, and restore instantly—anytime, anywhere. Grab this deal now before it disappears!

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
sql server query? 6 28
How to simplify my SQL statement? 14 21
Split Data in 1 column into 2 columns 8 21
Update in Sql 7 0
Everyone has problem when going to load data into Data warehouse (EDW). They all need to confirm that data quality is good but they don't no how to proceed. Microsoft has provided new task within SSIS 2008 called "Data Profiler Task". It solve th…
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now