Call now: (800) 766-1884  



 Home


 SQL Server Tips
 SQL Server Training

 SQL Server Consulting
 SQL Server Support
 SQL Server Remote DBA



 Articles
 Services
 SQL Server Scripts
 Scripts Menu



 

 

 

   
  SQL Server Tips by Gama and Naughter

 

Subqueries

 

A subquery is a SELECT statement within parentheses and included in a SELECT, INSERT, UPDATE, DELETE, another subquery or as part of a statement (if only one scalar is returned). There are two types of subquerys: correlated and non-correlated.

 

Correlated subqueries

 

As the outer query is executed, correlated subqueries are executed once for every row. This behavior is caused by the fact that the subquery uses data from the outer query, therefore, it needs to be updated for each row from the outer query.

 

Example: get titles that obtained a royalty from sales higher than the average of its range based royalty. In other words, what titles sold so much that they went above their average royalty.

 

SELECT DISTINCT TOP 100 PERCENT dbo.titles.title, dbo.titles.royalty

FROM  dbo.titles

where dbo.titles.royalty>

(SELECT AVG(royalty) FROM  dbo.roysched WHERE (title_id =dbo.titles.title_id))

ORDER BY dbo.titles.title

 

Non-correlated subqueries

 

As the outer query is executed, non-correlated subqueries are executed only once. The data from the outer query and the subquery are independent and one execution of the subquery will work for all the rows from the outer query.

 

Example: get titles that obtained a royalty from sales higher than the average of the minimum and maximum range based royalties. In other words, what titles went above the average of the highest and lowest royalties from all titles.

 

SELECT  TOP 100 PERCENT dbo.titles.title, dbo.titles.royalty

FROM  dbo.titles

where dbo.titles.royalty>

(SELECT (min(royalty)+max(royalty))/2 FROM  dbo.roysched )

ORDER BY dbo.titles.title


The above book excerpt is from:

Super SQL Server Systems
Turbocharge Database Performance with C++ External Procedures

ISBN: 0-9761573-2-2
Joseph Gama, P. J. Naughter

 http://www.rampant-books.com/book_2005_2_sql_server_external_procedures.htm
 

 

Burleson Consulting Remote DB Administration


 

 


 

 

 

 

 
Burleson is the America's Team

Note: The pages on this site were created as a support and training reference for use by our staff of DBA consultants.  If you find it confusing, please exit this page.

Errata?  SQL Server technology is changing and we strive to update our SQL Server support information.  If you find an error or have a suggestion for improving our content, we would appreciate your feedback.  Just  e-mail:and include the URL for the page.
 


Burleson Consulting
SQL Server database support

 

Copyright 1996 -  2013 by Vaaltech Web Services. All rights reserved.

Hit Counter