I noticed when writing a sproc values inserted into a table variable were in a different order than insertion. Is there a way to disable this auto sorting without adding another column for sorting? Ideas that come to mind are an automatic index being created or some collation setting... any ideas?
Visit http://sqlfiddle.com/#!3/e1c06/13 to see exactly what I mean
declare @tmpTbl table (name varchar(100))
insert into @tmpTbl
select 'mark'
union
select 'frank'
union
select 'sharon'
union
select 'jason'
select * from @tmpTbl
The short answer is (probably) "because the storage engine is storing your rows in an unordered heap, and that effects how the rows come out when you do not specify ORDER BY."
Unless you supply an ORDER BY in your SELECT query, sort order is undefined, per the SQL spec. That's the way it is in every SQL database, be it MySql, Oracle, or SQL Server. If data comes out of a table in the order you expect, that's by coincidence, or, most likely, a side effect of how the optimizer happened to generate the query, or how the storage engine chose to store the rows physically (as is probably the root cause in this case).
If you add a clustered index to the table in the sort order you want, many times, but not always, the table will come out in the order you expect. Do not ever rely on this behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With