Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase

Sort Order when SELECT FROM Table Variables Expand / Collapse
Author
Message
Posted Tuesday, June 7, 2011 8:22 AM
Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Friday, June 14, 2013 3:08 AM
Points: 14, Visits: 70
Hi,

Would I be correct in thinking that if you omit an ORDER BY clause when querying a Table variable in TSQL that you cannot guarantee the order in which the resulting records will be returned? That is, the Query Optimizer treats them the same as a normal user table.

For example, the output from the following TSQL would not guarantee a result set ordered by Col1:

--Insert into a table variable in order of Column 1, asceding.
INSERT @aTable
SELECT
Col1
, Col2
, Col3
FROM
anotherTable
ORDER BY
Col1

--Select from the table variable with no ORDER BY clause.
SELECT
*
FROM
@aTable


Thanks!
Post #1121053
Posted Tuesday, June 7, 2011 8:23 AM


SSC-Insane

SSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-Insane

Group: General Forum Members
Last Login: Today @ 1:06 AM
Points: 20,585, Visits: 9,625
There are 0 exceptions to that rule. If you want order by you MUST use order by.
Post #1121055
Posted Tuesday, June 7, 2011 8:33 AM
Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Friday, June 14, 2013 3:08 AM
Points: 14, Visits: 70
Great, thanks!
Post #1121060
« Prev Topic | Next Topic »

Add to briefcase

Permissions Expand / Collapse