0

Say I have the following query

SELECT * 
FROM foo 
WHERE P_KEY IN (5,7,2,6);

When I enter the query, the P_KEY values return the rows in the order of 2,5,6,7. How can I make it so it returns the rows in the order I entered it in the IN clause

This

P_KEY
5
7
2
6

NOT This

P_KEY
2
5
6
7
Yusuf Jama
  • 123
  • 13

2 Answers2

0

You can't directly order by the order of items in the IN clause. You'll have to create a temporary table or in-line sub-query to add an order to the values:

SELECT Foo.* FROM FOO
INNER  JOIN
(
   SELECT 5 AS [Key], 1 AS [Order]
   UNION ALL
   SELECT 7 AS [Key], 2 AS [Order]
   UNION ALL
   SELECT 2 AS [Key], 3 AS [Order]
   UNION ALL
   SELECT 6 AS [Key], 4 AS [Order]
) j
ON P_KEY = j.key
ORDER BY j.[Order]
D Stanley
  • 149,601
  • 11
  • 178
  • 240
0

A simple and not so elegant solution is to use UNION

SELECT * FROM foo WHERE P_KEY =5
UNION
SELECT * FROM foo WHERE P_KEY =7
UNION
SELECT * FROM foo WHERE P_KEY =2
UNION
SELECT * FROM foo WHERE P_KEY =6
JustAPup
  • 1,720
  • 12
  • 19
  • Is (5,7,2,6) something that a user selects, to be passed on as parameters to a stored procedure? If so, you can build the SQL by looping through those values. The proposed action above is more of a cheap and quick way to take care of your temporary problem, but I agree, in the long run you will need something more sophisticated :) – JustAPup Apr 19 '16 at 20:44