Module 5: Working with Subqueries. Writing Basic Subqueries Writing Correlated Subqueries Comparing Subqueries with Joins and Temporary Tables Using Common.

Slides:



Advertisements
Similar presentations
Chapter 4 Joining Multiple Tables
Advertisements

Module 4: Joining Data from Multiple Tables. Querying Multiple Tables by Using Joins Applying Joins for Typical Reporting Needs Combining and Limiting.
February 18, 2012 Lesson 3 Standard SQL. Lesson 3 Standard SQL.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Group functions cannot be used in the WHERE clause: SELECT type_code FROM d_songs WHERE SUM (duration) = 100; (this will give an error)
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.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
18 Copyright © Oracle Corporation, All rights reserved. Advanced Subqueries.
Introduction to Oracle9i: SQL1 Subqueries. Introduction to Oracle9i: SQL2 Chapter Objectives Determine when it is appropriate to use a subquery Identify.
Slides adapted from A. Silberschatz et al. Database System Concepts, 5th Ed. SQL - part 2 - Database Management Systems I Alex Coman, Winter 2006.
Database Systems More SQL Database Design -- More SQL1.
02 | Advanced SELECT Statements Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
CSE314 Database Systems More SQL: Complex Queries, Triggers, Views, and Schema Modification Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson.
Module 7 Reading SQL Server® 2008 R2 Execution Plans.
Module 9 Designing and Implementing Stored Procedures.
DBMS Languages. Data Definition Language (DDL) Used to define the conceptual and internal schemas Includes constraint definition language (CDL) for describing.
SQL/Lesson 4/Slide 1 of 45 Using Subqueries and Managing Databases Objectives In this lesson, you will learn to: *Use subqueries * Use subqueries with.
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.
Module 18 Querying XML Data in SQL Server® 2008 R2.
Module 4 Designing and Implementing Views. Module Overview Introduction to Views Creating and Managing Views Performance Considerations for Views.
Module 3 Designing and Implementing Tables. Module Overview Designing Tables Working with Schemas Creating and Altering Tables.
Chapter 12 Subqueries and Merge Statements
Module 11 Authorizing Users to Access Resources. Module Overview Authorizing User Access to Objects Authorizing Users to Execute Code Configuring Permissions.
Module 7: Implementing Views. Overview Introducing Views Defining and Using Views Using Views to Optimize Performance.
Chapter 13 Views Oracle 10g: SQL. Oracle 10g: SQL2 Objectives Create a view, using CREATE VIEW command or the CREATE OR REPLACE VIEW command Employ the.
Views, Algebra Temporary Tables. Definition of a view A view is a virtual table which does not physically hold data but instead acts like a window into.
6 Copyright © 2007, Oracle. All rights reserved. Retrieving Data Using Subqueries.
In this session, you will learn to: Query data by using joins Query data by using subqueries Objectives.
Manipulating Data Lesson 3. Objectives Queries The SELECT query to retrieve or extract data from one table, how to retrieve or extract data by using.
Database Programming Sections 6 –Subqueries, Single Row Subqueries, Multiple-row Subqueries, Correlated Subqueries.
Module 10 Merging Data and Passing Tables. Module Overview Using the MERGE Statement Implementing Table Types Using Table Types As Parameters.
Module 9: Using Advanced Techniques. Considerations for Querying Data Working with Data Types Cursors and Set-Based Queries Dynamic SQL Maintaining Query.
Module 2: Querying and Filtering Data. Using the SELECT Statement Filtering Data Working with NULL Values Formatting Result Sets Performance Considerations.
Module 8: Using Programming Objects for Data Retrieval.
Module 6: Modifying Data in Tables. Inserting Data into Tables Deleting Data from Tables Updating Data in Tables Overview of Transactions.
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 3: Grouping and Summarizing Data. Summarizing Data by Using Aggregate Functions Summarizing Grouped Data Ranking Grouped Data Creating Crosstab.
Module 9: Implementing Functions. Overview Creating and Using Functions Working with Functions Controlling Execution Context.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
6 Copyright © 2006, Oracle. All rights reserved. Retrieving Data Using Subqueries.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Structured Query Language
Module 4: Joining Data from Multiple Tables
MySQL Subquery Source: Dev.MySql.com
Chapter 12 Subqueries and MERGE Oracle 10g: SQL
Prepared by : Moshira M. Ali CS490 Coordinator Arab Open University
02 | Advanced SELECT Statements
Subqueries Schedule: Timing Topic 25 minutes Lecture
20761A 10: Using Subqueries Module 10   Using Subqueries.
Module 7: Implementing Views
05 | Using Functions and Aggregating Data
20761A 11: Using Set Operators Module 11   Using Set Operators.
Using Subqueries to Solve Queries
Writing Correlated Subqueries
Module 5: Implementing Data Integrity by Using Constraints
06 | Using Subqueries and APPLY
07 | Using Table Expressions
20761B 10: Using Subqueries Module 10   Using Subqueries.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
C1. SQL BAsic.
The Hidden Mysteries of Common Table Expressions
Contents Preface I Introduction Lesson Objectives I-2
Chapter 8 Advanced SQL.
Subqueries Schedule: Timing Topic 25 minutes Lecture
Retrieving Data by Using Subqueries
Database Systems: Design, Implementation, and Management Tenth Edition
Subqueries Schedule: Timing Topic 25 minutes Lecture
Grouping and Aggregating Data
Presentation transcript:

Module 5: Working with Subqueries

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

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

What Are Subqueries? Queries nested inside a SELECT, INSERT, UPDATE, or DELETE statement Can be used anywhere an Expression is allowed SELECT ProductID, Name FROM Production.Product WHERE Color NOT IN (SELECT Color FROM Production.Product WHERE ProductID = 5) SELECT ProductID, Name FROM Production.Product WHERE Color NOT IN (SELECT Color FROM Production.Product WHERE ProductID = 5) ProductID Name Adjustable Race 2 Bearing Ball... (504 row(s) affected) ProductID Name Adjustable Race 2 Bearing Ball... (504 row(s) affected) Result Set: Example:

Using Subqueries as Expressions 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 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 A Subquery can be substituted anywhere an expression can be used in the following statements, except in an ORDER BY list: SELECT UPDATE INSERT DELETE Example: Name ListPrice Average Difference Mountain-100 Silver, Mountain-100 Silver, (32 row(s) affected) Name ListPrice Average Difference Mountain-100 Silver, Mountain-100 Silver, (32 row(s) affected) Result Set:

Using the ANY, ALL, and SOME Operators Comparison operators that introduce a subquery can be modified by the keywords ALL or ANY SELECT Name FROM Production.Product WHERE ListPrice >= ANY (SELECT MAX (ListPrice) FROM Production.Product GROUP BY ProductSubcategoryID) SELECT Name FROM Production.Product WHERE ListPrice >= ANY (SELECT MAX (ListPrice) FROM Production.Product GROUP BY ProductSubcategoryID) SOME is an ISO standard equivalent for ANY SELECT Name FROM Production.Product WHERE ListPrice >= ALL (SELECT MAX (ListPrice) FROM Production.Product GROUP BY ProductSubcategoryID) SELECT Name FROM Production.Product WHERE ListPrice >= ALL (SELECT MAX (ListPrice) FROM Production.Product GROUP BY ProductSubcategoryID) Name LL Mountain Seat ML Mountain Seat... (304 row(s) affected) Name LL Mountain Seat ML Mountain Seat... (304 row(s) affected) Name Road-150 Red, 62 Road-150 Red, (5 row(s) affected) Name Road-150 Red, 62 Road-150 Red, (5 row(s) affected) ANY Example: ALL Example: Result Sets

Scalar versus Tabular Subqueries 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) 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) A scalar subquery returns a single row of data, while a tabular subquery returns multiple rows of data SELECT Name FROM Production.Product WHERE ListPrice = (SELECT ListPrice FROM Production.Product WHERE Name = 'Chainring Bolts' ) SELECT Name FROM Production.Product WHERE ListPrice = (SELECT ListPrice FROM Production.Product WHERE Name = 'Chainring Bolts' ) a b (0 row(s) affected) a b (0 row(s) affected) Name Adjustable Race Bearing Ball... (200 row(s) affected) Name Adjustable Race Bearing Ball... (200 row(s) affected) Scalar Subquery: Tabular Subquery: Result Sets

Rules for Writing 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 Subquery Allowances Subqueries can be specified in many places A subquery can itself include one or more subqueries

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

Lesson 2: Writing Correlated Subqueries What Are Correlated Subqueries? Building a Correlated Subquery Using Correlated Subqueries Using the EXISTS Clause with Correlated Subqueries

What Are Correlated Subqueries? Outer query passes column values to 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 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 1 1 Inner query uses that value to satisfy the inner query 2 2 Inner query returns a value back to the outer query 3 3 The process is repeated for the next row of the outer query 4 4 Back to Step 1

Building a Correlated Subquery SELECT c.LastName, c.FirstName FROM Person.Person c JOIN HumanResources.Employee e ON e.BusinessEntityID = c.BusinessEntityID WHERE IN (SELECT Bonus FROM Sales.SalesPerson sp WHERE e.BusinessEntityID = sp.BusinessEntityID) ; SELECT c.LastName, c.FirstName FROM Person.Person c JOIN HumanResources.Employee e ON e.BusinessEntityID = c.BusinessEntityID WHERE IN (SELECT Bonus FROM Sales.SalesPerson sp WHERE e.BusinessEntityID = sp.BusinessEntityID) ; SELECT Bonus FROM Sales.SalesPerson SELECT Bonus FROM Sales.SalesPerson SELECT c.LastName, c.FirstName FROM Person.Person c JOIN HumanResources.Employee e ON e.BusinessEntityID = c.BusinessEntityID SELECT c.LastName, c.FirstName FROM Person.Person c JOIN HumanResources.Employee e ON e.BusinessEntityID = c.BusinessEntityID Inner Query Outer Query Correlated Subquery +

Using Correlated Subqueries SELECT DISTINCT c.LastName, c.FirstName FROM Person.Person c JOIN HumanResources.Employee e ON e.BusinessEntityID = c.BusinessEntityID WHERE IN (SELECT Bonus FROM Sales.SalesPerson sp WHERE e.BusinessEntityID = sp.BusinessEntityID); SELECT DISTINCT c.LastName, c.FirstName FROM Person.Person c JOIN HumanResources.Employee e ON e.BusinessEntityID = c.BusinessEntityID WHERE IN (SELECT Bonus FROM Sales.SalesPerson sp WHERE e.BusinessEntityID = sp.BusinessEntityID); Example: LastNameFirstName Ansman-WolfePamela SaraiveJosé (2 row(s) affected) LastNameFirstName Ansman-WolfePamela SaraiveJosé (2 row(s) affected) Result Set: Correlated subqueries are executed repeatedly, once for each row that may be selected by the outer query

Using the EXISTS Clause with Correlated Subqueries SELECT Name FROM Production.Product WHERE EXISTS (SELECT * FROM Production.ProductSubcategory WHERE ProductSubcategoryID = Production.Product.ProductSubcategoryID AND Name = 'Wheels') SELECT Name FROM Production.Product WHERE EXISTS (SELECT * FROM Production.ProductSubcategory WHERE ProductSubcategoryID = Production.Product.ProductSubcategoryID AND Name = 'Wheels') When a subquery is introduced with the keyword EXISTS, the subquery functions as an existence test Name LL Mountain Front Wheel ML Mountain Front Wheel... (14 row(s) affected) Name LL Mountain Front Wheel ML Mountain Front Wheel... (14 row(s) affected) Result Set: Example:

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

Lesson 3: Comparing Subqueries with Joins and Temporary Tables Subqueries versus Joins Temporary Tables Subqueries versus Temporary Tables

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

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 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 ) CREATE TABLE #StoreInfo ( EmployeeID int, ManagerID int, Num int ) CREATE TABLE ##StoreInfo ( EmployeeID int, ManagerID int, Num int ) CREATE TABLE ##StoreInfo ( EmployeeID int, ManagerID int, Num int )

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

Lesson 4: Using Common Table Expressions What Are Common Table Expressions? Writing Common Table Expressions Writing Recursive Queries by Using Common Table Expressions

What Are Common Table Expressions? Result set can be used in SELECT, INSERT, UPDATE, or DELETE 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 A named temporary result set based on a SELECT query Common Table Expression

Writing Common Table Expressions Choose a CTE name and column list 1 1 WITH TopSales (SalesPersonID, NumSales) AS (SELECT SalesPersonID, Count(*) FROM Sales.SalesOrderHeader GROUP BY SalesPersonId) Create the CTE SELECT query 2 2 Use the CTE in a query 3 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

Writing Recursive Queries by Using Common Table Expressions Modify CTE SELECT query when creating CTE: Create the anchor member query (top of recursion tree) 1 1 SELECT ManagerID, EmployeeID FROM HumanResources.Employee WHERE ManagerID IS NULL Add the UNION ALL operator 2 2 SELECT ManagerID, EmployeeID FROM HumanResources.Employee WHERE ManagerID IS NULL UNION ALL Create the recursive member query that self-references the CTE 3 3 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

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

Lab: Working with SubqueriesPage 195 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 machineNY-SQL-01 User nameAdministrator Password Pa$$w0rd Estimated time: 60 minutes

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?

Module Review and Takeaways Review Questions Best Practices