?
Solved

Preserve return order WHERE IN

Posted on 2009-06-29
5
Medium Priority
?
316 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 450 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 450 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

Learn how to optimize MySQL for your business need

With the increasing importance of apps & networks in both business & personal interconnections, perfor. has become one of the key metrics of successful communication. This ebook is a hands-on business-case-driven guide to understanding MySQL query parameter tuning & database perf

Question has a verified solution.

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

Recently we ran in to an issue while running some SQL jobs where we were trying to process the cubes.  We got an error saying failure stating 'NT SERVICE\SQLSERVERAGENT does not have access to Analysis Services. So this is a way to automate that wit…
In part one, we reviewed the prerequisites required for installing SQL Server vNext. In this part we will explore how to install Microsoft's SQL Server on Ubuntu 16.04.
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…
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
Suggested Courses

770 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