Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Is results order mapped to values in 'IN' expression?

Tags:

sql

I have a list of record IDs for which I want to retrieve a single value from a table in SQL Server 2008.

My query is:

SELECT TestResult.FailureDetails FROM TestResult WHERE TestResult.ID IN (1,2,3,...)

The 'IN' expression contains hundreds of IDs. The ID column is the primary key of the table.

If my table is like:

ID    Value
1     A
2     B
3     C

Will I always get results ordered by order of appearance in the 'IN' expression? If not, I am considering doing:

SELECT TestResult.ID, TestResult.FailureDetails FROM TestResult WHERE TestResult.ID IN (1,2,3,...)
like image 795
siger Avatar asked Dec 21 '25 06:12

siger


1 Answers

No, you will not always get results in order based on the IN.

Be explicit, and add an ORDER BY clause.

SELECT FailureDetails 
FROM TestResult 
WHERE ID IN (1,2,3,...) 
ORDER BY ID;
like image 106
p.campbell Avatar answered Dec 22 '25 23:12

p.campbell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!