<

Go Premium for a chance to win a PS4. Enter to Win

x

Does SELECT retrieve rows in the order they are inserted ( Back to Basics -1 ) ?

Published on
11,017 Points
4,117 Views
4 Endorsements
Last Modified:
In SQL Server, when rows are selected from a table, does it retrieve data in the order in which it is inserted?  Many believe this is the case.

Let us try to examine for ourselves with an example.

To get started, use the following script, which I ran on my sever to create a table OrderTest in database TempDB and, additionally, to insert 4 rows into the table.
USE TempDB 
GO
CREATE TABLE OrderTest(N1 INT NOT NULL, C1 VARCHAR(100) NOT NULL)
GO 
INSERT INTO OrderTest(N1, C1) VALUES(1, 'First Insert') 
GO 
INSERT INTO OrderTest(N1, C1) VALUES(10, 'Second Insert') 
GO 
INSERT INTO OrderTest(N1, C1) VALUES(2, 'Third Insert') 
GO 
INSERT INTO OrderTest(N1, C1) VALUES(4, 'Fourth Insert') 
GO 

Open in new window


We are ready for the test.  Let us select data from the table.
USE TempDB 
GO
SELECT * FROM OrderTest 
GO

Open in new window

TestOutput1The results are indeed retrieved in the order in which it is inserted.  Convinced?

Now I am going to add a primary key to the table.
USE TempDB 
GO
ALTER TABLE OrderTest ADD PRIMARY KEY(N1)
GO 

Open in new window


With the primary key in place, let us once again select data from the table using the previous select statement.
USE TempDB 
GO
SELECT * FROM OrderTest 
GO

Open in new window

TestOutput2The rows are NOT returned in the order in which it is inserted!!  Surprising??

What made the difference?  

In the first case, the SQL Server query optimizer decided to do a table scan while it opted for a Clustered Index Scan in the latter case.   See the following execution plans for an illustration.
 ExecutionPlan1 ExecutionPlan2
The verdict.

SQL server does not guarantee any order of output (unless you explicitly append an ORDER BY clause to the query to order your output in a desired way added).  Further, it is the SQL Server query optimizer that decides how the data should be retrieved.  Hence never assume that data will be returned in the order in which it is inserted.
4
Comment
0 Comments

Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Join & Write a Comment

Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
Loops Section Overview

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month