SQL: ¿Se asigna el orden de resultados a los valores en la expresión 'IN'?

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

Mi consulta es:

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,...)

preguntado el 08 de noviembre de 11 a las 17:11

Do you always want in order of ID as per your example or do you need to support arbitrary orders? -

In order of the ID would have been fine. Per the answer below, I am now selecting TestResult.ID as well. -

2 Respuestas

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

Be explicit, and add an ORDER BY cláusula.

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

respondido 08 nov., 11:21

I would be surprised if they were ordered by the IN clause. As you've got no ORDER BY you'll probably get the results in PK order, but I wouldn't depend on that either.

If order is important you should set it explicitly:

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

respondido 08 nov., 11:21

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.