Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Preserve return order WHERE IN

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

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

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…
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.
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
Viewers will learn how the fundamental information of how to create a table.

610 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