views:

359

answers:

3

I have a SELECT query that yields multiple results and do not have any ORDER BY clause. If I execute this query multiple times and then iterate through results using DataReader.NextResult(), would I be guaranteed to get the results in the same order?

For e.g. if I execute the following query that return 199 rows:

SELECT * FROM products WHERE productid < 200

would I always get the first result with productid = 1 and so on?

As far as I have observed it always return the results in same order, but I cannot find any documentation for this behavior.

======================================

As per my research: Check out this blog Conor vs. SQL. I actually wanted to ask if the query-result changes even if the data in table remains the same (i.e no update or delete). But it seems like in case of large table, when SQL server employees parallelism, the order can be different

+3  A: 

No, DataReader will return the results in the order they come back from SQL. If you don't specify an ORDER BY clause, that will be the order that they exist in the table.

Rory
I agree with Rory. If you want it in a specific order then you should add an Order By in your SQL statement.
Walter
+5  A: 

First of all, to iterate the rows in a DataReader, you should call Read, not NextResult.
Calling NextResult will move to the next result set if your query has multiple SELECT statements.

To answer your question, you must not rely on this.
A query without an ORDER BY clause will return rows in SQL Server's default iteration order.
For small tables, this will usually be the order in which the rows were added, but this is not guaranteed and is liable to change at any time. For example, if the table is indexed or partitioned, the order will be different.

SLaks
+1  A: 

It is possible, perhaps even likely that they will always return in the same order, but this isn't guaranteed. The order is determined by the queryplan (at least in SQL Server) on the database server. If something changes that queryplan, the order could change. You should always use ORDER BY if the order of results is in anyway important to your processing of the data.

BBlake

related questions