Results 1 to 6 of 6

Thread: How to ORDER BY designated list of key values

  1. #1
    Join Date
    Apr 2006
    Posts
    3

    How to ORDER BY designated list of key values

    I need to be able to order the results of a SELECT query by the order of a specific list of key IDs provided in the WHERE IN statement.

    So my query looks like:

    SELECT *
    FROM TableName
    WHERE KeyID IN (3,104,43,22,345)
    ORDER BY ????

    I need the results returned in the order provided in the IN list (3,104,43,22,345).

    Thanks in advance!

    pr0

  2. #2
    Join Date
    Sep 2002
    Posts
    5,938
    You can only order by column, not values of the column. Try use union to put them together in your designated order.

  3. #3
    Join Date
    Apr 2006
    Posts
    3

    how's that?

    I'm not quite sure how to use UNION for that purpose. Could you elaborate? Thanks!

  4. #4
    Join Date
    Apr 2006
    Posts
    30
    Code:
    SELECT *
    FROM TableName
    WHERE KeyID IN (3,104,43,22,345)
    ORDER BY
    	Case KeyID
    		WHEN 3 Then 1
    		WHEN 104 Then 2
    		WHEN 43 Then 3
    		WHEN 22 Then 4
    		WHEN 345 Then 5
    	End

  5. #5
    Join Date
    Apr 2006
    Posts
    3

    It worked!

    Thanks russellb! That was the perfect solution. I never would have figured that one out.

    pr0

  6. #6
    Join Date
    Apr 2006
    Posts
    30
    glad 2 help. the other way, which i think rm was going after is this
    Code:
    select *, 1 as sortVal from table where KeyID = 3
    UNION
    select *, 2 as sortVal from table where KeyID = 104
    UNION
    select *, 3 as sortVal from table where KeyID = 43
    ...
    ORDER BY sortVal

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •