Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Example:
SELECT ProductID, Name FROM Production.Product WHERE Color NOT IN (SELECT Color FROM Production.Product WHERE ProductID = 5)
Result Set:
ProductID Name -------------------------------------1 Adjustable Race 2 Bearing Ball ... (504 row(s) affected)
Example:
SELECT UPDATE
INSERT DELETE
SELECT Name, ListPrice, (SELECT AVG(ListPrice) FROM Production.Product) AS Average, ListPrice (SELECT AVG(ListPrice) FROM Production.Product) AS Difference FROM Production.Product WHERE ProductSubcategoryID = 1
Result Set:
Name ListPrice Average Difference --------------------------------------------------------Mountain-100 Silver, 38 3399.99 438.6662 2961.3238 Mountain-100 Silver, 42 3399.99 438.6662 2961.3238 ... (32 row(s) affected)
ANY Example:
SELECT Name FROM Production.Product WHERE ListPrice >= ANY (SELECT MAX (ListPrice) FROM Production.Product GROUP BY ProductSubcategoryID)
Result Sets
Name --------------------LL Mountain Seat ML Mountain Seat ... (304 row(s) affected)
ALL Example:
SELECT Name FROM Production.Product WHERE ListPrice >= ALL (SELECT MAX (ListPrice) FROM Production.Product GROUP BY ProductSubcategoryID)
Scalar Subquery:
create table T1 (a int, b int) create table T2 (a int, b int) select * from T1 where T1.a > (select max(T2.a) from T2 where T2.b < T1.b)
Result Sets
a b ---------------------... (0 row(s) affected)
Tabular Subquery:
SELECT Name FROM Production.Product WHERE ListPrice = (SELECT ListPrice FROM Production.Product WHERE Name = 'Chainring Bolts' )
Subquery Restrictions
SELECT list of a subquery introduced with a comparison operator can include only one expression WHERE clauses must be join-compatible ntext, text, and image data types cannot be used Column names in a statement are implicitly qualified by the table referenced in the FROM clause
The process is repeated for the next row of the outer query
Back to Step 1
Inner Query
Correlated Subquery
SELECT c.LastName, c.FirstName FROM Person.Person c JOIN HumanResources.Employee e ON e.BusinessEntityID = c.BusinessEntityID WHERE 5000.00 IN (SELECT Bonus FROM Sales.SalesPerson sp WHERE e.BusinessEntityID = sp.BusinessEntityID) ;
Example:
SELECT DISTINCT c.LastName, c.FirstName FROM Person.Person c JOIN HumanResources.Employee e ON e.BusinessEntityID = c.BusinessEntityID WHERE 5000.00 IN (SELECT Bonus FROM Sales.SalesPerson sp WHERE e.BusinessEntityID = sp.BusinessEntityID);
Result Set:
LastName FirstName ----------------------------Ansman-Wolfe Pamela Saraive Jos (2 row(s) affected)
Example:
SELECT Name FROM Production.Product WHERE EXISTS (SELECT * FROM Production.ProductSubcategory WHERE ProductSubcategoryID = Production.Product.ProductSubcategoryID AND Name = 'Wheels')
Result Set:
Name -----------------------LL Mountain Front Wheel ML Mountain Front Wheel ... (14 row(s) affected)
Joins can yield better performance in some cases where existence must be checked Joins are performed faster by SQL Server than subqueries Subqueries can often be rewritten as joins SQL Server 2008 query optimizer is intelligent enough to covert a subquery into a join if it can be done Subqueries are useful for answering questions that are too complex to answer with joins
Temporary Tables
As subqueries get more complex their performance may decrease Maintainability can be easier with subqueries in some situations, and easier with temporary tables in others Temporary tables can be easier for some to debug while others prefer to work with a single subquery
Expressions
Queries with derived tables become more readable Provide traversal of recursive hierarchies
WITH TopSales (SalesPersonID, NumSales) AS ( SELECT SalesPersonID, Count(*) FROM Sales.SalesOrderHeader GROUP BY SalesPersonId ) SELECT * FROM TopSales WHERE SalesPersonID IS NOT NULL ORDER BY NumSales DESC
1 2 3
WITH TopSales (SalesPersonID, NumSales) AS (SELECT SalesPersonID, Count(*) FROM Sales.SalesOrderHeader GROUP BY SalesPersonId) SELECT LoginID, NumSales FROM HumanResources.Employee e INNER JOIN TopSales ON TopSales.SalesPersonID = e.EmployeeID ORDER BY NumSales DESC
1 2 3
Create the anchor member query (top of recursion tree) Add the UNION ALL operator Create the recursive member query that self-references the CTE
SELECT ManagerID, EmployeeID FROM HumanResources.Employee WHERE ManagerID IS NULL UNION ALL SELECT e.ManagerID, e.EmployeeID FROM HumanResources.Employee e INNER JOIN HumanResources.Employee mgr ON e.ManagerID = mgr.EmployeeID
Temporary Tables
Exercise 4: Using Common Table Expressions
Logon information
Lab Scenario
You are a database developer at Adventure Works. You have
been asked by several managers of the company to prepare a number of reports in order to help the executive committee determine the budget for next year.
Lab Review
How are basic subqueries evaluated? How are correlated subqueries evaluated? What could a Common Table Expression be used for?