Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 SELECT and the order of a result set

Author  Topic 

dmilam
Posting Yak Master

185 Posts

Posted - 2012-11-27 : 15:43:40
When SELECT is called, say in


SELECT PersonID
FROM dbo.Persons


, the database engine orders the display of the resulting data based on how the pages are currently allocated, if I'm using the correct terms?

It doesn't appear to be (pseudo)random since each time I run the query above, it returns the IDs in a certain order, but not in ascending numeric order as I might expect with an index.

For example, these five IDs currently are at the top, rows 1 - 5

66555
68181
68422
69194
65956

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2012-11-27 : 15:51:29
quote:
Originally posted by dmilam

When SELECT is called, <snip>, the database engine orders the display of the resulting data based on how the pages are currently allocated, if I'm using the correct terms?
No, that is just a coincidence. SQL makes no guarantee about the order of the result set unless and ORDER BY clause is used.

EDIT: Missing word.
Go to Top of Page

dmilam
Posting Yak Master

185 Posts

Posted - 2012-11-27 : 16:50:06
OK, thanks, then it can be said to be pseudo-random, I suppose. Trying to explain to others why this is so, but I don't know enough about the internals of the database engine to point to any documentation.
Go to Top of Page

jimf
Master Smack Fu Yak Hacker

2875 Posts

Posted - 2012-11-27 : 17:28:01
Think of this way. Our concept of order is 1,2,3,4,5, etc. SQL's is "this is the first one I got, this the second one I got, etc.". If you run the same query many times in a row, SQL server says "I just got that, so here it is again." so you get the same order. After many insert/updates to the table, you may get a different result in your first 5 records. SO the only to guarantee our concept of order is to tell SQL explicitly how we want things ordered

Jim

Everyday I learn something that somebody else already knew
Go to Top of Page

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2012-11-27 : 17:32:31
Yeah, there are a bunch of ways that can cause SQL to return rows out of clustered order. I can think of about 5 or so off the top of my head and I'm sure there are many more. You might try doing a search if you wanted more detail to help with documenting the deifferent reasons.
Go to Top of Page

dmilam
Posting Yak Master

185 Posts

Posted - 2012-11-27 : 19:06:51
OK, thanks all
Go to Top of Page
   

- Advertisement -