Solved

Preserve return order WHERE IN

Posted on 2009-06-29
5
307 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

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

786 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