1

I have a query that I execute on a sqlconnection and create a reader from the SqlCommand.ExecuteReader. I'm doing a simple Select * from table. I am not using an order by, but the results from the query when run in management studio always come back in the same order. 1 2 3 4 But when I do a reader.Read() the order is not the same. I see a random record being pulled out. 3 2 4 1 Anyone have an idea of why this might happen?

1
  • 1
    Because you aren't using an order by clause. Without using one, you get results back in an arbitrary order. SSMS and the reader might give different orderings for a number of reasons. Commented Jun 20, 2013 at 16:12

1 Answer 1

4

If you don't say ORDER BY, ADO.NET is free to return the rows in any order it wants. Why do you complain?

People often incorrectly assume that without an ORDER BY the order of the rows would be the clustered index... or if they use a GROUP BY that it will be in this order... or other arbitrary rules.

These assumptions sometimes hold, sometimes not and always rely on implementation details and specific execution plans.

The only way to get a guaranteed ordering of your results is to use ORDER BY. Anything else is wrong, or you don't care about the order.

BTW, this doesn't always imply a performance hit for sorting. SQL Server is quite clever and if it knows the rows are already sorted (e.g. because it reads them out of an index based upon your ORDER BY columns), it will do nothing.

Sign up to request clarification or add additional context in comments.

2 Comments

I am not complaining, just asking. Your answer is good enough, thanks
@jw56578 Sorry, I'm not a native English speaker and it was not meant to be offensive. Just a way of saying "you didn't ask for a specific order -- you got none -- what did you expect?"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.