Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL 2008 - resultset order issue

We are using SQL Server 2008. We have a table called response which has a primary key called response_id. It also has a column called bid_id. When we execute the query

‘select * from response where bid_id = x’

without an ‘order by’ we are getting results in mostly ascending order (default), but once in a while in descending order (very random). Is it possible in sql that the same sql query might return a resultset in different order if executed several times without order by? We used to have SQL Server 2000 till 5 months ago and never faced this problem. Does SQL Server 2008 deal differently with sql queries without ‘order by’?

Thanks.

like image 386
spie Avatar asked Jan 22 '26 00:01

spie


2 Answers

In any SQL statement, on any database, you need to define an ORDER BY clause to guarantee the order is consistent.

like image 89
OMG Ponies Avatar answered Jan 24 '26 19:01

OMG Ponies


Do you mean this happens for varying values of x?

As OMG Ponies says the order is not guaranteed unless you specify one.

In terms of an explanation perhaps you are getting a clustered index scan when it thinks there will be a significant portion of rows matching the bid_id = x criteria, hence them being in order of response_id, but it is looking them up via a non clustered index on the bid_id column when it expects fewer records to match the condition. These different access strategies could lead to them being returned in different orders. Adding an ORDER BY would cause it to favour a strategy that will leave them sorted or it would add an additional sort step to the plan before the results get returned.

like image 26
Martin Smith Avatar answered Jan 24 '26 20:01

Martin Smith