Sei sulla pagina 1di 31

Slide 1

Module 5: Working with Subqueries

Slide 2

Module 5: Working with Subqueries


Writing Basic Subqueries Writing Correlated Subqueries Comparing Subqueries with Joins and Temporary Tables Using Common Table Expressions

Slide 3

Lesson 1: Writing Basic Subqueries


What Are Subqueries? Using Subqueries as Expressions Using the ANY, ALL, and SOME Operators Scalar versus Tabular Subqueries Rules for Writing Subqueries

Slide 4

What Are Subqueries?

Queries nested inside a SELECT, INSERT, UPDATE, or DELETE statement Can be used anywhere an Expression is allowed

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)

Use this slide to introduce the concepts involved in subqueries. A subquery is a query that is nested inside a SELECT, INSERT, UPDATE, or DELETE statement, or inside another subquery. A subquery can be used anywhere an expression is allowed. A subquery is also called an inner query or inner select, while the statement containing a subquery is also called an outer query or outer select. The SELECT query of a subquery is always enclosed in parentheses. Additional points of interest A subquery can be nested inside the WHERE or HAVING clause of an outer SELECT, INSERT, UPDATE, or DELETE statement, or inside another subquery. Up to 32 levels of nesting is possible, although the limit varies based on available memory and the complexity of other expressions in the query. Individual queries may not support nesting up to 32 levels. A subquery can appear anywhere an expression can be used, if it returns a single value. References Subquery Fundamentals: http://go.microsoft.com/fwlink/?LinkID=127318

Slide 5

Using Subqueries as Expressions


A Subquery can be substituted anywhere an expression can be used in the following statements, except in an ORDER BY list:


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)

Use this slide to describe how to use subqueries as expressions. In Transact-SQL, a subquery can be substituted anywhere an expression can be used in SELECT, UPDATE, INSERT, and DELETE statements, except in an ORDER BY list. The example shown here illustrates how you might use this enhancement. This query finds the prices of all mountain bike products, their average price, and the difference between the price of each mountain bike and the average price. References Subqueries Used in Place of an Expression: http://go.microsoft.com/fwlink/?LinkID=127319

Slide 6

Using the ANY, ALL, and SOME Operators


Comparison operators that introduce a subquery can be modified by the keywords ALL or ANY

SOME is an ISO standard equivalent for ANY

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)

Name -------------------Road-150 Red, 62 Road-150 Red, 44... (5 row(s) affected)

Use this slide to describe how to use the ANY, ALL, and SOME operators with subqueries. Comparison operators that introduce a subquery can be modified by the keywords ALL or ANY. SOME is an ISO standard equivalent for ANY. Subqueries introduced with a modified comparison operator return a list of zero or more values and can include a GROUP BY or HAVING clause. Using the > comparison operator as an example, >ALL means greater than every value. In other words, it means greater than the maximum value. For a row in a subquery with >ALL to satisfy the condition specified in the outer query, the value in the column introducing the subquery must be greater than each value in the list of values returned by the subquery. Similarly, >ANY means that for a row to satisfy the condition specified in the outer query, the value in the column that introduces the subquery must be greater than at least one of the values in the list of values returned by the subquery. The sample query shown here provides an example of a subquery introduced with a comparison operator modified by ANY. It finds ANY products whose list prices are greater than or equal to the maximum list price of any product subcategory. The second sample query shows how ALL operates differently than ANY. See how ALL returns only those products whose list price is greater than or equal to all the list prices returned in the inner query. References Comparison Operators Modified by ANY, SOME, or ALL: http://go.microsoft.com/fwlink/?LinkID=127320

Slide 7

Scalar versus Tabular Subqueries


A scalar subquery returns a single row of data, while a tabular subquery returns multiple rows of data

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' )

Name -----------------Adjustable Race Bearing Ball ... (200 row(s) affected)

Use this slide to discuss the differences between scalar and tabular subqueries. A scalar subquery is a subquery that returns a single row of data, whereas a tabular subquery returns multiple rows of data. Code box 1 (top) The subquery in this example uses an aggregate that ensures that it produces only a single row on each execution. (Of course, due to the correlation, this single row may be different for each for of T1.) As you might expect, this plan works by scanning each row of T1 and with the help of the nested loops join evaluating the subquery once for each row. Since the subquery always produces exactly one row, the number of rows output of the join is precisely equal to the number of rows in T1. Finally, we use the filter to evaluate the WHERE clause of the original query and to determine whether to return each row. Code box 2 (bottom) This is a standard subquery that returns tabular data. References Craig Freedmans SQL Server Blog: http://go.microsoft.com/fwlink/?LinkID=127321

Slide 8

Rules for Writing Subqueries


Subquery Allowances
Subqueries can be specified in many places A subquery can itself include one or more subqueries

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 this slide to discuss subquery restrictions, subquery types, qualifying column names, and multiple levels of nesting. Review the list of subquery restrictions including the following: The select list of a subquery introduced with a comparison operator can include only one expression or column name (except that EXISTS and IN operate on SELECT * or a list, respectively). If the WHERE clause of an outer query includes a column name, it must be join-compatible with the column in the subquery select list. The ntext, text, and image data types cannot be used in the select list of subqueries. Subqueries can be specific in many places: with aliases, with IN or NOT IN; in UPDATE, DELETE, and INSERT statements; with comparison operators; with ANY, SOME, or ALL; with EXISTS or NOT EXISTS; in place of an expression. The general rule is that column names in a statement are implicitly qualified by the table referenced in the FROM clause at the same level. If a column does not exist in the table referenced in the FROM clause of a subquery, it is implicitly qualified by the table referenced in the FROM clause of the outer query. A subquery can itself include one or more subqueries. Any number of subqueries can be nested in a statement. References Subquery Rules: http://go.microsoft.com/fwlink/?LinkID=127322 Qualifying Column Names in Subqueries: http://go.microsoft.com/fwlink/?LinkID=127323

Slide 9

Demonstration: Writing Basic Subqueries


In this demonstration, you will see how to:
Write a Basic Subquery Use the ANY, ALL, and SOME Operators

In this demonstration, show how to write a basic subquery. Also demonstrate how to use the ANY, ALL, and SOME operators. Start SQL Server Management Studio and, using the AdventureWorks2008 database, perform each of the queries found in E:\MOD05\Democode\WritingBasicSubqueries.sql. How would you rewrite the basic subquery demonstrated to you here as a join? SELECT Prd1.Name FROM Production.Product AS Prd1 JOIN Production.Product AS Prd2 ON (Prd1.ListPrice = Prd2.ListPrice) WHERE Prd2. Name = Freewheel' What results were returned by the SELECT statement that contained an ANY expression and why? The products whose list prices are greater than or equal to the maximum list price of any product subcategory. References Comparison Operators Modified by ANY, SOME, or ALL: http://go.microsoft.com/fwlink/?LinkID=127320

Slide 10

Lesson 2: Writing Correlated Subqueries


What Are Correlated Subqueries? Building a Correlated Subquery Using Correlated Subqueries Using the EXISTS Clause with Correlated Subqueries

Slide 11

What Are Correlated Subqueries? 1


Outer query passes column values to the inner query

Inner query uses that value 2 to satisfy the inner query 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

Inner query returns a value back to the outer query

The process is repeated for the next row of the outer query

Back to Step 1

Use this slide to describe how correlated subqueries work. Many queries can be evaluated by executing the subquery once and substituting the resulting value or values into the WHERE clause of the outer query. In queries that include a correlated subquery (also known as a repeating subquery), the subquery depends on the outer query for its values. This means that the subquery is executed repeatedly, once for each row that might be selected by the outer query. Delivery note: if students do not understand the definition, explain that a correlated subquery is a subquery that contains a reference to a column or columns in the outer query, and that correlated subqueries are also called repeating subqueries because they are executed multiple times during processing - one time for each row in the outer query. Correlated subqueries can also include table-valued functions in the FROM clause by referencing columns from a table in the outer query as an argument of the table-valued function. In this case, for each row of the outer query, the table-valued function is evaluated according to the subquery. References Correlated Subqueries: http://go.microsoft.com/fwlink/?LinkID=127324

Slide 12

Building a Correlated Subquery


Outer Query
SELECT c.LastName, c.FirstName FROM Person.Person c JOIN HumanResources.Employee e ON e.BusinessEntityID = c.BusinessEntityID

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) ;

Use this slide to describe how to build a correlated subquery. Code box 1 (top-left, beneath Outer Query) A subquery depends on the outer query for its values. Because of this, building a correlated subquery involves creating both an outer and inner query. Here we have an outer query that retrieves each employee's first and last name. Code box 2 (top-right, beneath Inner Query) This is an inner query that retrieves each bonus amount for all salespeople. Adding it to the outer query will create the correlated subquery that appears in the next step. Note that this inner query does need to be rewritten in order for it to make sense in the correlated subquery. Code box 3 (bottom, beneath Correlated Subquery) Here weve combined the two queries into a correlated subquery. This query retrieves one instance of each employee's first and last name for which the bonus in the SalesPerson table is 5000 and for which the employee identification numbers (BusinessEntityID) match in the Employee and SalesPerson tables. SQL Server considers each row of the Employee table for inclusion in the results by substituting the value in each row into the inner query. See how the inner query shown had to be rewritten to fit the JOIN of the outer query. References Correlated Subqueries: http://go.microsoft.com/fwlink/?LinkID=127324

Slide 13

Using Correlated Subqueries


Correlated subqueries are executed repeatedly, once for each row that may be selected by the outer query

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)

Use this slide to describe how to write repeating queries by using correlated subqueries. A correlated subquery is also known as a repeating subquery, where the subquery depends on the outer query for its values. This means that the subquery is executed repeatedly, once for each row that might be selected by the outer query. This is a query that depends on the outer query for its values. The query is executed repeatedly, one time for each row that may be selected by the outer query. This query retrieves one instance of the first and last name of each employee for which the bonus in the SalesPerson table is 5000.00 and for which the employee identification numbers match in the Employee and SalesPerson tables. References Correlated Subqueries: http://go.microsoft.com/fwlink/?LinkID=127324

Slide 14

Using the EXISTS Clause with Correlated Subqueries


When a subquery is introduced with the keyword EXISTS, the subquery functions as an existence test

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)

Use this slide to explain how to use the EXISTS clause with correlated subqueries. When a subquery is introduced with the keyword EXISTS, the subquery functions as an existence test. The WHERE clause of the outer query tests whether the rows that are returned by the subquery exist. The subquery does not actually produce any data; it returns a value of TRUE or FALSE. This query finds the names of all products that are in the Wheels subcategory. To understand the results of this query, consider the name of each product in turn. Does this value cause the subquery to return at least one row? In other words, does the query cause the existence test to evaluate to TRUE? The EXISTS keyword is important because frequently there is no alternative, nonsubquery formulation. Although some queries that are created with EXISTS cannot be expressed any other way, many queries can use IN or a comparison operator modified by ANY or ALL to achieve similar results. References Subqueries with EXISTS: http://go.microsoft.com/fwlink/?LinkID=127325

Slide 15

Demonstration: Writing Correlated Subqueries


In this demonstration, you will see how to:
Write a Correlated Subquery Create a Correlated Subquery with Comparison Operators

In this demonstration, show how to build a correlated subquery and how to use the EXISTS clause. Start SQL Server Management Studio and, using the AdventureWorks2008 database, perform each of the queries found in E:\MOD05\Democode\WritingCorrelatedSubqueries.sql. What is the process behind building a correlated subquery? This is defined back on the slide titled What are Correlated Subqueries? What results did the correlated subqueries return? Sales where the quantity is less than the average quantity for sales of that product. References Correlated Subqueries: http://go.microsoft.com/fwlink/?LinkID=127324 SELECT Examples (Transact-SQL): http://go.microsoft.com/fwlink/?LinkID=127253

Slide 16

Lesson 3: Comparing Subqueries with Joins and Temporary Tables


Subqueries versus Joins Temporary Tables Subqueries versus Temporary Tables

Slide 17

Subqueries versus Joins


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

Use this slide to discuss the differences between subqueries and joins. In Transact-SQL, there is usually no performance difference between a statement that includes a subquery and a semantically equivalent version that does not. However, in some cases where existence must be checked, a join yields better performance. Otherwise, the nested query must be processed for each result of the outer query to ensure elimination of duplicates. In such cases, a join approach would yield better results. Generally speaking, subqueries are written to answer questions that are too complex to answer with joins or, more appropriately, are easier to write with a subquery than a join. It is often easier to see nesting and query organization in a subquery than it is in a query that requires a number of joins to arrive at the same conclusion if that query with multiple joins can even duplicate the subquery in the first place. References Join Fundamentals: http://go.microsoft.com/fwlink/?LinkID=127326 Subquery Fundamentals: http://go.microsoft.com/fwlink/?LinkID=127318

Slide 18

Temporary Tables
Local Temporary Tables:
Have a single number sign (#) as the first character of their names CREATE TABLE #StoreInfo ( EmployeeID int, ManagerID int, Num int )

Visible only to the current connection for the user


Deleted when the user disconnects from SQL Server

Global Temporary Tables:


Have a double number sign (##) as the first character of their names

Visible to any user once created


Deleted when all users referencing them disconnect

CREATE TABLE ##StoreInfo ( EmployeeID int, ManagerID int, Num int )

Use this slide to discuss the differences between subqueries and temporary tables. Temporary tables are similar to permanent tables, except temporary tables are stored in tempdb and are deleted automatically when they are no longer used. Local temporary tables have a single number sign (#) as the first character of their names, are visible only to the current connection for the user, and they are deleted when the user disconnects from the instance of SQL Server. Global temporary tables have two number signs (##) as the first characters of their names, are visible to any user after they are created, and they are deleted when all users referencing the table disconnect from the instance of SQL Server. Describe how a temporary table might be used in practice. Consider reading from the following script: If you create the table StoreInfo, the table can be used by any person who has the security permissions in the database to use it, until the table is deleted. If a database session creates the local temporary table #StoreInfo, only the session can work with the table, and it is deleted when the session disconnects. If you create the global temporary table ##StoreInfo, any user in the database can work with this table. If no other user works with this table after you create it, the table is deleted when you disconnect. If another user works with the table after you create it, SQL Server deletes it after you disconnect and after all other sessions are no longer actively using it. References Special Table Types: http://go.microsoft.com/fwlink/?LinkID=127327 Creating and Modifying Table Basics: http://go.microsoft.com/fwlink/?LinkID=127328

Slide 19

Subqueries versus 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

Use this slide to discuss the differences between subqueries and temporary tables. Performance is one issue when comparing temp tables and subqueries. As subqueries get more complex their performance may decrease. On the other hand, as more temp tables are created, that may also take additional time (increased I/O) also decreasing performance. Subqueries are appropriate when you have a lot of RAM while temporary tables are geared towards database servers with a lot of hard disk space because temp tables require more I/O when executing, which can be very expensive while subqueries occur in memory. However, you can index temp tables, which would help with performance on large tables. Maintainability is also a consideration. Depending on the number of temp tables generated, the resulting query can get quite complicated increasing maintenance in the long run. However, if the subquery is really complex, it can be easier and more maintainable to store intermediate values in a temp tables and filter through the data that way. The same could be said for debugging. Temporary tables can be easier for some to debug while others like to have a single query (with subqueries) when debugging. References Database Performance: http://go.microsoft.com/fwlink/?LinkID=127329

Slide 20

Lesson 4: Using Common Table Expressions


What Are Common Table Expressions? Writing Common Table Expressions Writing Recursive Queries by Using Common Table

Expressions

Slide 21

What Are Common Table Expressions?


Common Table Expression
or DELETE

A named temporary result set based on a SELECT query

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

Use this slide to describe how common table expressions work. A common table expression (CTE) can be thought of as a temporary result set that is defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement. A CTE is similar to a derived table in that it is not stored as an object and lasts only for the duration of the query. Unlike a derived table, a CTE can be selfreferencing and can be referenced multiple times in the same query. A CTE is made up of an expression name representing the CTE, an optional column list, and a query defining the CTE. After a CTE is defined, it can be referenced like a table or view can in a SELECT, INSERT, UPDATE, or DELETE statement. A CTE can also be used in a CREATE VIEW statement as part of its defining SELECT statement. A CTE can be used to: Create a recursive query. Substitute for a view when the general use of a view is not required; that is, you do not have to store the definition in metadata. Enable grouping by a column that is derived from a scalar subselect, or a function that is either not deterministic or has external access. Reference the resulting table multiple times in the same statement. References Using Common Table Expressions: http://go.microsoft.com/fwlink/?LinkID=127330

Slide 22

Writing Common Table Expressions


1
Choose a CTE name and column list Create the CTE SELECT query

2
3

Use the CTE in a query

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

Use this slide to describe how to write common table expressions. Using a CTE offers the advantages of improved readability and ease in maintenance of complex queries. The query can be divided into separate, simple, logical building blocks. These simple blocks can then be used to build more complex, interim CTEs until the final result set is generated. To build a CTE, you must first choose a CTE name and column list. Then, create the CTE SELECT query. Finally, use the CTE in a query, which youll see in the demonstration later in this lesson. References Using Common Table Expressions: http://go.microsoft.com/fwlink/?LinkID=127330

Slide 23

Writing Recursive Queries by Using Common Table Expressions


Modify CTE SELECT query when creating CTE:

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

Use this slide to describe how to write recursive queries using common table expressions. A common table expression (CTE) provides the significant advantage of being able to reference itself, thereby creating a recursive CTE. A recursive CTE is one in which an initial CTE is repeatedly executed to return subsets of data until the complete result set is obtained. A query is referred to as a recursive query when it references a recursive CTE. Returning hierarchical data is a common use of recursive queries, for example: Displaying employees in an organizational chart, or data in a bill of materials scenario in which a parent product has one or more components and those components may, in turn, have subcomponents or may be components of other parents. A recursive CTE can greatly simplify the code required to run a recursive query within a SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement. In earlier versions of SQL Server, a recursive query usually requires using temporary tables, cursors, and logic to control the flow of the recursive steps. The structure of the recursive CTE in Transact-SQL is similar to recursive routines in other programming languages. Although a recursive routine in other languages returns a scalar value, a recursive CTE can return multiple rows. A recursive CTE consists of three elements: Invocation of the routine. The first invocation of the recursive CTE consists of one or more CTE_query_definitions joined by UNION ALL, UNION, EXCEPT, or INTERSECT operators. Because these query definitions form the base result set of the CTE structure, they are referred to as anchor members. CTE_query_definitions are considered anchor members unless they reference the CTE itself. All anchor-member query definitions must be positioned before the first recursive member definition, and a UNION ALL operator must be used to join the last anchor member with the first recursive member.

Recursive invocation of the routine. The recursive invocation includes one or more CTE_query_definitions joined by UNION ALL operators that reference the CTE itself. These query definitions are referred to as recursive members. Termination check. The termination check is implicit; recursion stops when no rows are returned from the previous invocation. References Recursive Queries Using Common Table Expressions: http://go.microsoft.com/fwlink/?LinkID=127331

Slide 24

Demonstration: Using Common Table Expressions


In this demonstration, you will see how to:
Write a Common Table Expression Write a Recursive Query

In this demonstration, show how to write a common table expression and how to write a recursive query. Start SQL Server Management Studio and, using the AdventureWorks2008 database, perform each of the queries found in E:\MOD05\Democode\Sales_CTE.sql and then E:\MOD05\Democode\ProductBOM.sql. In the first demonstration, how many times was the CTE referenced when the statement was executed and why? When the statement was executed, the CTE was referenced two times: one time to return the selected columns for the salesperson, and again to retrieve similar details for the salesperson's manager. The data for both the salesperson and the manager were returned in a single row. What would happen if you created a recursive CTE that returned the same values for both the parent and child columns? You would create an infinite loop. Note that, when testing the results of a recursive query, you can limit the number of recursion levels allowed for a specific statement by using the MAXRECURSION hint and a value between 0 and 32,767 in the OPTION clause of the INSERT, UPDATE, DELETE, or SELECT statement. References Using Common Table Expressions: http://go.microsoft.com/fwlink/?LinkID=127330 Recursive Queries Using Common Table Expressions: http://go.microsoft.com/fwlink/?LinkID=127331

Slide 25

Lab: Working with Subqueries


Exercise 1: Writing Basic Subqueries Exercise 2: Writing Correlated Subqueries Exercise 3: Comparing Subqueries with Joins and

Temporary Tables

Exercise 4: Using Common Table Expressions

Logon information

Virtual machine User name

NY-SQL-01 Administrator

Password

Pa$$w0rd

Estimated time: 60 minutes

In this lab, students will learn how to work with subqueries, including how to write basic subqueries, how to write correlated subqueries, how to compare subqueries with joins and temporary tables, and how to use common table expressions. Exercise 1 In this exercise, Exercise 2 In this exercise, Exercise 3 In this exercise, Exercise 4 In this exercise, students will write basic subqueries. students will write correlated subqueries. students will compare subqueries with joins and temporary tables. students will use common table expressions.

Before the students begin the lab, read the scenario associated with each exercise to the class. This will reinforce the broad issue that the students are troubleshooting and will help to facilitate the lab discussion at the end of the module. Remind the students to complete the discussion questions after the last lab exercise. Note: The lab exercise answer keys are provided on the Course Companion CD. To access the answer key, click the link located at the bottom of the relevant lab exercise page.

Slide 26

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.

Slide 27

Lab Review
How are basic subqueries evaluated? How are correlated subqueries evaluated? What could a Common Table Expression be used for?

Use the questions on the slide to guide the debriefing after students have completed the lab exercises. Question: How are basic subqueries evaluated? Answer: By executing the subquery once and substituting the resulting value or values into the WHERE clause of the outer query. Question: How are correlated subqueries evaluated? Answer: These subqueries depends on the query for their values. This means that the subquery is executed repeatedly, once for each row that might be selected in the outer query. Question: What could a Common Table Expression be used for? Answer: Creating a recursive query, substituting for a view when the general use of a view is not required, enabled grouping by a column that is derived from a scalar subselect, or referencing the resulting table multiple times in the same statement.

Slide 28

Module Review and Takeaways


Review Questions Best Practices

Review Questions Point the students to the appropriate section in the course so that they are able to answer the questions presented in this section. Question: A subquery nested in the outer SELECT statement has what components? Answer: A regular SELECT query including the regular select list components, a regular FROM clause including one or more table or view names, an optional WHERE clause, an optional GROUP BY clause, and an optional HAVING clause. Question: What clauses can the SELECT query of a subquery include? What clauses can it not include? Answer: The SELECT query of a subquery cannot include a COMPUTE or FOR BROWSE clause, and may only include an ORDER BY clause when a TOP clause is also specified. Question: What are the three basic types of subqueries? Answer: Those that operate on lists introduced with IN, or those that a comparison operator modified by ANY or ALL; those that are introduced with an unmodified comparison operator and must return a single value; those that are existence tests introduced with EXISTS. Best Practices related to Subqueries with EXISTS Help the students understand the best practices presented in this section. Ask students to consider these best practices in the context of their own business situations. Subqueries that are introduced with EXISTS are a bit different from other subqueries in the following ways: The keyword EXISTS is not preceded by a column name, constant, or other expression. The select list of a subquery introduced by EXISTS almost always consists of an asterisk (*). There is no reason to list column names because you are just testing whether rows that meet the conditions specified in the subquery exist.

The EXISTS keyword is important because frequently there is no alternative, nonsubquery formulation. Although some queries that are created with EXISTS cannot be expressed any other way, many queries can use IN or a comparison operator modified by ANY or ALL to achieve similar results.

Potrebbero piacerti anche