Solved

Preserve return order WHERE IN

Posted on 2009-06-29
5
310 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

The Eight Noble Truths of Backup and Recovery

How can IT departments tackle the challenges of a Big Data world? This white paper provides a roadmap to success and helps companies ensure that all their data is safe and secure, no matter if it resides on-premise with physical or virtual machines or in the cloud.

Question has a verified solution.

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

This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
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…
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

739 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