20761B 10: Using Subqueries Module 10   Using Subqueries.

Slides:



Advertisements
Similar presentations
© 2007 by Prentice Hall (Hoffer, Prescott & McFadden) 1 Joins and Sub-queries in SQL.
Advertisements

A Guide to SQL, Seventh Edition. Objectives Use joins to retrieve data from more than one table Use the IN and EXISTS operators to query multiple tables.
Group functions cannot be used in the WHERE clause: SELECT type_code FROM d_songs WHERE SUM (duration) = 100; (this will give an error)
SQL Subqueries Objectives of the Lecture : To consider the general nature of subqueries. To consider simple versus correlated subqueries. To consider the.
Module 6: Working with Subqueries. Overview Introduction to Subqueries Using a Subquery as a Derived Table Using a Subquery as an Expression Using a Subquery.
Introduction to Oracle9i: SQL1 Subqueries. Introduction to Oracle9i: SQL2 Chapter Objectives Determine when it is appropriate to use a subquery Identify.
1 DDL – subquery Sen Zhang. 2 Objectives What is a subquery? Learn how to create nested SQL queries Read sample scripts and book for different kinds of.
1 SQL-Structured Query Language SQL is the most common language used for creating and querying relational databases. Many users can access a database applications.
Advanced SQL SMSU Computer Services Short Course.
02 | Advanced SELECT Statements Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
Using Relational Databases and SQL Department of Computer Science California State University, Los Angeles Lecture 8: Subqueries.
Introduction to Databases Chapter 7: Data Access and Manipulation.
Advanced SQL Murat Kantarcioglu Adapted from Silberchatz et al. slides.
SQL advanced select using Oracle 1 7. Multiple Tables: Joins and Set Operations 8. Subqueries: Nested Queries.
1 Chapter 8: Advanced SQL. Chapter 8 2 Processing Multiple Tables – Joins Join – a relational operation that causes two or more tables with a common domain.
A Guide to MySQL 5. 2 Objectives Use joins to retrieve data from more than one table Use the IN and EXISTS operators to query multiple tables Use a subquery.
Database Programming Sections 6 –Subqueries, Single Row Subqueries, Multiple-column subqueries, Multiple-row Subqueries, Correlated Subqueries 11/2/10,
04 | Grouping and Aggregating Data Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida Introduction to SQL—Topics Introduction to.
Week 10 Quiz 9 Answers Group 28 Christine Hallstrom Deena Phadnis.
1 © Prentice Hall, 2002 Chapter 8: Advanced SQL Modern Database Management 6 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.
Module 18 Querying XML Data in SQL Server® 2008 R2.
Unit 4 Queries and Joins. Key Concepts Using the SELECT statement Statement clauses Subqueries Multiple table statements Using table pseudonyms Inner.
Chapter 12 Subqueries and Merge Statements
Module 3: Using XML. Overview Retrieving XML by Using FOR XML Shredding XML by Using OPENXML Introducing XQuery Using the xml Data Type.
In this session, you will learn to: Query data by using joins Query data by using subqueries Objectives.
Database Programming Sections 6 –Subqueries, Single Row Subqueries, Multiple-row Subqueries, Correlated Subqueries.
Chapter 7 Subqueries. Chapter Objectives  Determine when it is appropriate to use a subquery  Identify which clauses can contain subqueries  Distinguish.
Slide 1 of 32ASH-Training Querying and Managing Data Using SQL Server 2014 By: Segla In this session, you will learn to: Query data by using joins Query.
Module 9: Implementing Functions. Overview Creating and Using Functions Working with Functions Controlling Execution Context.
Select Complex Queries Database Management Fundamentals LESSON 3.1b.
Lecture 7: Subqueries Tarik Booker California State University, Los Angeles.
Module 5: Working with Subqueries. Writing Basic Subqueries Writing Correlated Subqueries Comparing Subqueries with Joins and Temporary Tables Using Common.
Using Subqueries to Solve Queries
Boost your T-SQL with the APPLY Operator
More SQL: Complex Queries,
Chapter 12 Subqueries and MERGE Oracle 10g: SQL
Multiple Table Queries
02 | Advanced SELECT Statements
Subqueries.
Subqueries Schedule: Timing Topic 25 minutes Lecture
Sorting and Filtering Data
Querying Multiple Tables
20761A 10: Using Subqueries Module 10   Using Subqueries.
20761A 11: Using Set Operators Module 11   Using Set Operators.
Using Subqueries to Solve Queries
Sorting and Filtering Data
Writing Correlated Subqueries
Querying Multiple Tables
06 | Using Subqueries and APPLY
20761B 12: Using Set Operators Module 12   Using Set Operators.
Writing SELECT Queries
07 | Using Table Expressions
Aggregations Various Aggregation Functions GROUP BY HAVING.
Using Table Expressions
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Using Subqueries to Solve Queries
Reporting Aggregated Data Using the Group Functions
Chapter 8 Advanced SQL.
Subqueries Schedule: Timing Topic 25 minutes Lecture
Using Subqueries to Solve Queries
Database Systems: Design, Implementation, and Management Tenth Edition
Reporting Aggregated Data Using the Group Functions
Using Subqueries to Solve Queries
Reporting Aggregated Data Using the Group Functions
Subqueries Schedule: Timing Topic 25 minutes Lecture
Subqueries Schedule: Timing Topic 25 minutes Lecture
Pivoting and Grouping Sets
Grouping and Aggregating Data
Presentation transcript:

20761B 10: Using Subqueries Module 10   Using Subqueries

Using the EXISTS Predicate with Subqueries Module Overview 10: Using Subqueries Using the EXISTS Predicate with Subqueries  

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.

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.

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.

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

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

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.

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;

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;

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 “*”.

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 http://aka.ms/q812le WHERE [NOT] EXISTS (subquery)

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