20761B 12: Using Set Operators Module 12   Using Set Operators.

Slides:



Advertisements
Similar presentations
Using the Set Operators
Advertisements

Advanced SQL (part 1) CS263 Lecture 7.
© 2007 by Prentice Hall (Hoffer, Prescott & McFadden) 1 Joins and Sub-queries in SQL.
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.
Relational Algebra, Join and QBE Yong Choi School of Business CSUB, Bakersfield.
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 SQL Session 2 Retrieving Data From Multiple Tables.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 8 Advanced SQL.
Inner join, self join and Outer join Sen Zhang. Joining data together is one of the most significant strengths of a relational database. A join is a query.
Chapter 11.1 and 11.2 Data Manipulation: Relational Algebra and SQL Brian Cobarrubia Introduction to Database Management Systems October 4, 2007.
02 | Advanced SELECT Statements Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
SQL Joins.
Version 1.0. MCAD MCSD MCPD Enterprise SQL MCTS MCT Software/Web Development Consultant Cryptography/Digital Signature Consultant SQL Server 2005/2008R2/2012.
Database Systems: Design, Implementation, and Management Tenth Edition Chapter 8 Advanced SQL.
Introduction to Databases Chapter 7: Data Access and Manipulation.
Module 7 Reading SQL Server® 2008 R2 Execution Plans.
Chapter 9 Joining Data from Multiple Tables
04 | Grouping and Aggregating Data Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
JOINS cis 407 Inner join Right and left outer join Full join Cross join.
Chapter 4 Multiple-Table Queries
Unit 4 Queries and Joins. Key Concepts Using the SELECT statement Statement clauses Subqueries Multiple table statements Using table pseudonyms Inner.
XP Chapter 3 Succeeding in Business with Microsoft Office Access 2003: A Problem-Solving Approach 1 Analyzing Data For Effective Decision Making Chapter.
1 Multiple Table Queries. 2 Objectives  Retrieve data from more than one table by joining tables  Using IN and EXISTS to query multiple tables  Nested.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Advanced Relational Algebra & SQL (Part1 )
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.
A Guide to SQL, Eighth Edition Chapter Five Multiple-Table Queries.
05 | SET Operators, Windows Functions, and Grouping Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program.
In this session, you will learn to: Query data by using joins Query data by using subqueries Objectives.
Query Processing – Implementing Set Operations and Joins Chap. 19.
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.
Thinking in Sets and SQL Query Logical Processing.
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.
BTM 382 Database Management Chapter 8 Advanced SQL Chitu Okoli Associate Professor in Business Technology Management John Molson School of Business, Concordia.
Select Complex Queries Database Management Fundamentals LESSON 3.1b.
LEC-8 SQL. Indexes The CREATE INDEX statement is used to create indexes in tables. Indexes allow the database application to find data fast; without reading.
Advanced SQL Advanced Database Dr. AlaaEddin Almabhouh.
IFS180 Intro. to Data Management Chapter 10 - Unions.
Boost your T-SQL with the APPLY Operator
Instructor: Craig Duckett Lecture 09: Tuesday, April 25th, 2017
02 | Advanced SELECT Statements
Sorting and Filtering Data
Database Systems: Design, Implementation, and Management Tenth Edition
Querying Multiple Tables
20761A 10: Using Subqueries Module 10   Using Subqueries.
Using the Set Operators
20761A 11: Using Set Operators Module 11   Using Set Operators.
03 | Querying Multiple Tables with Joins
Sorting and Filtering Data
Querying Multiple Tables
06 | Using Subqueries and APPLY
04 | Using Set Operators Graeme Malcolm | Senior Content Developer, Microsoft Geoff Allix | Principal Technologist, Content Master.
David M. Kroenke and David J
20761B 12: Using Set Operators Module 12   Using Set Operators.
Using the Set Operators
Writing SELECT Queries
07 | Using Table Expressions
20761B 10: Using Subqueries Module 10   Using Subqueries.
JOINS (Joinining multiple tables)
Using Table Expressions
SQL Fundamentals in Three Hours
Using Subqueries to Solve Queries
Contents Preface I Introduction Lesson Objectives I-2
Chapter 8 Advanced SQL.
Database Systems: Design, Implementation, and Management Tenth Edition
Using the Set Operators
Manipulating Data Lesson 3.
JOINS (Joinining multiple tables)
Pivoting and Grouping Sets
Grouping and Aggregating Data
Presentation transcript:

20761B 12: Using Set Operators Module 12   Using Set Operators

20761B Module Overview 12: Using Set Operators Using APPLY  

Lesson 1: Writing Queries with the UNION Operator 20761B Lesson 1: Writing Queries with the UNION Operator 12: Using Set Operators Demonstration: Using UNION and UNION ALL Question True or false? The results from a UNION query can contain duplicate rows. ( )False ( )True Answer (√)False When combining the output of two sets, UNION and UNION ALL queries cannot include rows with NULL values, because NULL values cannot be compared.

Interactions Between Sets 12: Using Set Operators The results of two input queries may be further manipulated Sets may be combined, compared, or operated against each other Both sets must have the same number of compatible columns ORDER BY not allowed in input queries, but may be used for result of set operation NULLs considered equal when comparing sets This module builds on the set theory discussion from Module 2 of this course. Consider calling attention to the note at the bottom of this topic, along with the additional references provided in the module Introduction to Transact-SQL Querying. More information on set theory and its application to SQL Server queries can be found in T-SQL Querying (Developer Reference) - Itzik Ben-Gan et al (Microsoft Press, 2015). <SELECT query_1> <set_operator> <SELECT query_2> [ORDER BY <sort_list>];

Using the UNION Operator 20761B Using the UNION Operator 12: Using Set Operators UNION returns a result set of distinct rows combined from both input sets Duplicates are removed during query processing (affects performance) The Venn diagram uses the blue to represent rows returned from the Employees table. The blue color signifies that the query will return all records from Employees and those that also occur in Customers. Note that duplicates are filtered by UNION, regardless of which input result sets they occur in. To be filtered, duplicate data does not have to exist in both input result sets. If you are comfortable with execution plans and feel that the class won’t be too confused, consider displaying and comparing the execution plans from the UNION example in this topic and the UNION ALL example in the next one. Employees Customers -- only distinct rows from both queries are returned SELECT country, region, city FROM HR.Employees UNION SELECT country, region, city FROM Sales.Customers;

Using the UNION ALL Operator 20761B Using the UNION ALL Operator 12: Using Set Operators UNION ALL returns a result set with all rows from both input sets To avoid the performance penalty caused by filtering duplicates, use UNION ALL over UNION whenever requirements allow it   -- all rows from both queries will be returned SELECT country, region, city FROM HR.Employees UNION ALL SELECT country, region, city FROM Sales.Customers;

Lesson 2: Using EXCEPT and INTERSECT 20761B Lesson 2: Using EXCEPT and INTERSECT 12: Using Set Operators Demonstration: Using EXCEPT and INTERSECT Question You have a table of employees and a table of customers, both of which contain a column holding the name of the country where the customer or employee is located. You want to know which countries have at least one customer and at least one employee. Which set operator should you use? ( )Option 1: UNION ALL ( )Option 2: UNION ( )Option 3: EXCEPT ( )Option 4: INTERSECT ( )Option 5: None of the above Answer (√) Option -2: INTERSECT

Using the INTERSECT Operator 20761B Using the INTERSECT Operator 12: Using Set Operators INTERSECT returns the distinct set of rows that appear in both input result sets The Venn diagram uses the darker blue color to represent rows returned from the Employees table. All rows from Employees will be returned, when they are also found in the Customers table. Employees Customers -- only rows that exist in both queries will be returned SELECT country, region, city FROM HR.Employees INTERSECT SELECT country, region, city FROM Sales.Customers;

Using the EXCEPT Operator 20761B Using the EXCEPT Operator 12: Using Set Operators EXCEPT returns only distinct rows that appear in the left set but not the right The order in which sets are specified matters The Venn diagram uses the darker color (blue) to represent rows returned from the Employees table. All rows from Employees will be returned, except those found in the Customers table. Employees Customers -- only rows from Employees will be returned SELECT country, region, city FROM HR.Employees EXCEPT SELECT country, region, city FROM Sales.Customers;

Demonstration: Using CROSS APPLY and OUTER APPLY 20761B Lesson 3: Using APPLY 12: Using Set Operators Demonstration: Using CROSS APPLY and OUTER APPLY Students may have conceptual difficulties with APPLY. It may be helpful to discuss the logical similarity between CROSS APPLY and INNER JOIN, OUTER APPLY and OUTER JOIN before moving on to examples using table-valued functions (TVFs). It might also be useful to use the demonstration file examples as you go through the next three topics, rather than wait until the end. Question What is the difference between CROSS APPLY and CROSS JOIN? Answer CROSS JOIN returns all the possible combinations of the left and right table sources; CROSS APPLY returns only the values from the left table source where a value is found in the right table source.

Using the APPLY Operator 20761B Using the APPLY Operator 12: Using Set Operators APPLY is a table operator used in the FROM clause Two forms—CROSS APPLY and OUTER APPLY Operates on two input tables, referred to as left and right Right table may be any table expression including a derived table or a table-valued function Remind students that use of “left table” and “right table” in the context of APPLY refers to the order of the tables as listed in the FROM clause, much as in a JOIN. SELECT <column_list> FROM <left_table_source> AS <alias> [CROSS]|[OUTER] APPLY <right_table_source> AS <alias>;

The CROSS APPLY Operator 20761B The CROSS APPLY Operator 12: Using Set Operators CROSS APPLY applies the right table source to each row in the left table source Only rows with results in both the left table source and right table source are returned Most INNER JOIN statements can be rewritten as CROSS APPLY statements USE TSQL; GO SELECT o.orderid, o.orderdate, od.productid, od.unitprice, od.qty FROM Sales.Orders AS o INNER JOIN Sales.OrderDetails AS od ON o.orderid = od.orderid ; CROSS APPLY ( SELECT productid, unitprice, qty FROM Sales.OrderDetails AS so WHERE so.orderid = o.orderid ) AS od; If you are comfortable with query execution plans and feel that it won’t confuse the class, demonstrate that the execution plans for these statements are identical. SELECT o.orderid, o.orderdate, od.productid, od.unitprice, od.qty FROM Sales.Orders AS o CROSS APPLY (SELECT productid, unitprice, qty FROM Sales.OrderDetails AS so WHERE so.orderid = o.orderid ) AS od;

The OUTER APPLY Operator 20761B The OUTER APPLY Operator 12: Using Set Operators OUTER APPLY applies the right table source to each row in the left table source All rows from the left table source are returned—values from the right table source are returned where they exist, otherwise NULL is returned Most LEFT OUTER JOIN statements can be rewritten as OUTER APPLY statements USE TSQL; GO SELECT DISTINCT s.country AS supplier_country, c.country as customer_country FROM Production.Suppliers AS s LEFT OUTER JOIN Sales.Customers AS c ON c.country = s.country ORDER BY supplier_country; OUTER APPLY ( SELECT country FROM Sales.Customers AS cu WHERE cu.country = s.country ) AS c If you are comfortable with query execution plans and feel that it won’t confuse the class, demonstrate that, although the result sets returned by the queries match, the execution plans for these statements are different. In this case, the OUTER APPLY statement is slightly more efficient. SELECT DISTINCT s.country AS supplier_country, c.country as customer_country FROM Production.Suppliers AS s OUTER APPLY (SELECT country FROM Sales.Customers AS cu WHERE cu.country = s.country ) AS c ORDER BY supplier_country;

CROSS APPLY and OUTER APPLY Features 20761B CROSS APPLY and OUTER APPLY Features 12: Using Set Operators CROSS APPLY and OUTER APPLY allow query expressions that could not appear in a JOIN to return as part of a single result set For example, table-valued functions (TVFs)   SELECT S.supplierid, s.companyname, P.productid, P.productname, P.unitprice FROM Production.Suppliers AS S CROSS APPLY dbo.fn_TopProductsByShipper(S.supplierid) AS P;