Download presentation
Presentation is loading. Please wait.
Published byΣαῦλος Ευάγγελος Σαμαράς Modified over 6 years ago
1
20761B 10: Using Subqueries Module 10 Using Subqueries
2
Using the EXISTS Predicate with Subqueries
Module Overview 10: Using Subqueries Using the EXISTS Predicate with Subqueries
3
Lesson 1: Writing Self-Contained Subqueries
10: Using Subqueries Demonstration: Writing Self-Contained Subqueries Question You are troubleshooting a query. The outer query contains an inner query in its WHERE clause. The first inner query also contains a second inner query in its WHERE clause. Both inner queries are self- contained. The complete query returns an error. How should you approach this task? Answer Break the complete query into its constituent subqueries. Start with the innermost subquery and test to see if it returns the information you expect. Next, test the first inner query. Finally, test the complete query.
4
Working with Subqueries
10: Using Subqueries Subqueries are nested queries: queries within queries Results of inner query passed to outer query Inner query acts like an expression from perspective of outer query Subqueries can be self-contained or correlated Self-contained subqueries have no dependency on outer query Correlated subqueries depend on values from outer query Subqueries can be scalar, multi-valued, or table- valued Note that self-contained subqueries are easier to test when they are separated from the outer query.
5
Comparing Self-Contained and Correlated Subqueries
10: Using Subqueries Self-Contained Subquery: Correlated Subquery: Outer Query: SELECT orderid, productid, unitprice, qty FROM Sales.OrderDetails WHERE orderid = ( ) Inner Query: SELECT MAX(orderid) AS lastorder FROM Sales.Orders SELECT orderid, empid, orderdate FROM Sales.Orders AS O1 WHERE orderdate = ( ) SELECT MAX(orderdate) FROM Sales.Orders AS O2 WHERE O2.empid = O1.empid This slide illustrates the difference between self-contained and correlated subqueries. Do not go into specifics of the queries shown—you will cover that later in this module. Instead emphasize that, in self- contained subqueries, the inner query does not take information from the outer query. By contrast, in a correlated subquery, the inner query requires information from the outer query.
6
Writing Scalar Subqueries
10: Using Subqueries Scalar subquery returns single value to outer query Can be used anywhere single-valued expression is used: SELECT, WHERE, and so on If inner query returns an empty set, result is converted to NULL Construction of outer query determines whether inner query must return a single value The example returns details about the most recent order. This is the error returned if the inner query is not scalar and the outer is written to expect a single value: Msg 512, Level 16, State 1, Line 1 Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when it is used as an expression. SELECT orderid, productid, unitprice, qty FROM Sales.OrderDetails WHERE orderid = (SELECT MAX(orderid) AS lastorder FROM Sales.Orders);
7
Writing Multi-Valued Subqueries
10: Using Subqueries Multi-valued subquery returns multiple values as a single column set to the outer query Used with IN predicate If any value in the subquery result matches IN predicate expression, the predicate returns TRUE May also be expressed as a JOIN (test both for performance) The example returns information about orders placed by customers in Mexico. This may be rewritten as a JOIN: SELECT c.custid, o.orderid FROM Sales.Customers AS c JOIN Sales.Orders AS o ON c.custid = o.custid WHERE c.country = 'Mexico‘; Point out to the students that sometimes it’s easier to write and test a query one piece at a time, in which case a subquery may be more accessible. SELECT custid, orderid FROM Sales.orders WHERE custid IN ( SELECT custid FROM Sales.Customers WHERE country = N'Mexico');
8
Lesson 2: Writing Correlated Subqueries
10: Using Subqueries Demonstration: Writing Correlated Subqueries Question Which of the following statements about correlated subqueries is correct? ( )Option 1: To troubleshoot a correlated subquery, execute the inner query first on its own, before placing it into the outer query. ( )Option 2: In a correlated subquery, the inner query is run only once, regardless of the number of rows the outer query returns. ( )Option 3: In a correlated subquery, the inner query uses data returned by the outer query. ( )Option 4: In a correlated subquery, the inner query is executed first, the outer query second. Answer (√) Option -2: In a correlated subquery, the inner query uses data returned by the outer query.
9
Working with Correlated Subqueries
10: Using Subqueries Correlated subqueries refer to elements of tables used in outer query Dependent on outer query, cannot be executed separately Harder to test than self-contained subqueries Behaves as if inner query is executed once per outer row May return scalar value or multiple values The example above appears in the workbook, broken down step by step. Walk the students through it using the workbook notes. Question Why can't a correlated subquery be executed separately from the outer query? Answer The subquery depends on input from the outer query for its values. SELECT orderid, empid, orderdate FROM Sales.Orders AS O1 WHERE orderdate = (SELECT MAX(orderdate) FROM Sales.Orders AS O2 WHERE O2.empid = O1.empid) ORDER BY empid, orderdate;
10
Writing Correlated Subqueries
10: Using Subqueries Write inner query to accept input value from outer query Write outer query to accept appropriate return result (scalar or multi-valued) Correlate queries by passing value from outer query to match argument in inner query This example evaluates each row in Sales.Orders, takes the current row’s customer ID, and passes it to the inner query to find the most recent order for that customer ID. SELECT custid, orderid, orderdate FROM Sales.Orders AS outerorders WHERE orderdate = (SELECT MAX(orderdate) FROM Sales.Orders AS innerorders WHERE innerorders.custid = outerorders.custid) ORDER BY custid;
11
Lesson 3: Using the EXISTS Predicate with Subqueries
10: Using Subqueries Demonstration: Writing Subqueries Using EXISTS Question The Human Resources database has recently been extended to record the skills possessed by employees. Employees have added their skills to the database by using a web-based user interface. You want to find employees who have not yet added their skills. You have the following query: SELECT e.EmployeeID, e.FirstName FROM HumanResources.Employees AS e WHERE NOT EXISTS ( SELECT s.EmployeeID, s.SkillName, s.SkillCategory FROM HumanResources.Skills AS s WHERE e.EmployeeID = s.EmployeeID); How can you improve the query? Answer In the inner query SELECT clause, replace the list of columns with “*”.
12
EXISTS evaluates to TRUE or FALSE (not UNKNOWN)
20761B Working with EXISTS 10: Using Subqueries When a subquery is used with the keyword EXISTS, it functions as an existence test True or false only—no rows passed back to outer query EXISTS evaluates to TRUE or FALSE (not UNKNOWN) If any rows are returned by the subquery, EXISTS returns TRUE If no rows are returned, EXISTS returns FALSE Syntax: See Subqueries with EXISTS in the SQL Server 2016 Technical Documentation: Subqueries with EXISTS WHERE [NOT] EXISTS (subquery)
13
Writing Queries Using EXISTS with Subqueries
10: Using Subqueries The keyword EXISTS does not follow a column name or other expression The SELECT list of a subquery introduced by EXISTS typically only uses an asterisk (*) Note: the SELECT list typically only uses an asterisk because no data will be returned. The inner query tests to see if there are any rows in its results. It will not return the rows themselves. SELECT custid, companyname FROM Sales.Customers AS c WHERE EXISTS ( SELECT * FROM Sales.Orders AS o WHERE c.custid=o.custid); SELECT custid, companyname FROM Sales.Customers AS c WHERE NOT EXISTS ( SELECT * FROM Sales.Orders AS o WHERE c.custid=o.custid);
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.