SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 TOP clause in INSERT statement
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

mmkrishna1919
Yak Posting Veteran

India
88 Posts

Posted - 06/25/2013 :  04:36:01  Show Profile  Reply with Quote
Hi Team,
Data Base:AdventureworksLT2008

will below two statements insert same set of rows in a table?
insert top(5) into #test(id,name)
select CustomerID,firstname from SalesLT.Customer
order by CustomerID desc

insert into #test(id,name)
select top (5) CustomerID,firstname from SalesLT.Customer
order by CustomerID desc

And how optimiser will choose 5 rows to insert in first statement
Are those first 5 rows in result set of select statement?
Or
It will pick randomly?

Thanks.

M.MURALI kRISHNA

visakh16
Very Important crosS Applying yaK Herder

India
52317 Posts

Posted - 06/25/2013 :  04:41:14  Show Profile  Reply with Quote
It will choose 5 random rows (ie order not guaranteed) though actual order may depend on factors like presence of clustered index etc. Ie effect of using TOP N in insert will be to ignore the ORDER BY in select

In the second case its obvious, ie based on ORDER specified in ORDER BY

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

mmkrishna1919
Yak Posting Veteran

India
88 Posts

Posted - 06/25/2013 :  04:51:59  Show Profile  Reply with Quote
Thanks Visakh..

M.MURALI kRISHNA
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
52317 Posts

Posted - 06/25/2013 :  04:55:03  Show Profile  Reply with Quote
welcome

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.06 seconds. Powered By: Snitz Forums 2000