Professional Documents
Culture Documents
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
USE northwind SELECT orderid, customerid FROM orders AS or1 WHERE 20 < (SELECT quantity FROM [order details] AS od WHERE or1.orderid = od.orderid AND od.productid = 23) GO
The process is repeated for the next row of the outer query
Back to Step 1
Inner Query
SELECT Bonus FROM Sales.SalesPerson
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)
Temporary Tables
Local Temporary Tables:
Have a single number sign (#) as the first character of their names Visible only to the current connection for the user Deleted when the user disconnects from SQL Server CREATE TABLE #StoreInfo ( EmployeeID int, ManagerID int, Num int )
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
Result set can be used in SELECT, INSERT, UPDATE, Advantages of common table 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
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
Temporary Tables
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?