Querying Multiple Tables

Slides:



Advertisements
Similar presentations
Advanced SQL (part 1) CS263 Lecture 7.
Advertisements

Chapter 4 Joining Multiple Tables
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.
Writing Basic SQL SELECT Statements. Capabilities of SQL SELECT Statements A SELECT statement retrieves information from the database. Using a SELECT.
5 Copyright © 2004, Oracle. All rights reserved. Displaying Data from Multiple Tables.
Introduction to Structured Query Language (SQL)
Introduction to Oracle9i: SQL1 Basic SQL SELECT Statements.
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.
WRITING BASIC SQL SELECT STATEMENTS Lecture 7 1. Outlines  SQL SELECT statement  Capabilities of SELECT statements  Basic SELECT statement  Selecting.
02 | Advanced SELECT Statements Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
SQL Joins.
Learningcomputer.com SQL Server 2008 – Entity Relationships in a Database.
Using Relational Databases and SQL John Hurley Department of Computer Science California State University, Los Angeles Lecture 3: Joins Part I.
Chapter 9 Joining Data from Multiple Tables
Sections 3 – Joins & Hierarchical Queries
Joins. Joins In order to maintain normalization in the database design it is necessary to break up data into separate tables. The data can then be re-associated.
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.
JOI/1 Data Manipulation - Joins Objectives –To learn how to join several tables together to produce output Contents –Extending a Select to retrieve data.
CS146 References: ORACLE 9i PROGRAMMING A Primer Rajshekhar Sunderraman
Chapter 4Introduction to Oracle9i: SQL1 Chapter 4 Joining Multiple Tables.
Unit 4 Queries and Joins. Key Concepts Using the SELECT statement Statement clauses Subqueries Multiple table statements Using table pseudonyms Inner.
Relational Databases.  In week 1 we looked at the concept of a key, the primary key is a column/attribute that uniquely identifies the rest of the data.
Introduction to SQL PART Ⅰ 第一讲 Writing Basic SQL SELECT Statements.
Database Programming Sections 4 – Joins. Marge Hohly2 Overview  Oracle Proprietary Joins (8i and prior): Cartesian Product Equijoin Non-equijoin Outer.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
Displaying Data from Multiple Tables (SQL99 Syntax with examples)
1 Copyright © Oracle Corporation, All rights reserved. Writing Basic SQL SELECT Statements.
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.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
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.
1 Copyright © 2007, Oracle. All rights reserved. Retrieving Data Using the SQL SELECT Statement.
1 Copyright © 2009, Oracle. All rights reserved. Retrieving Data Using the SQL SELECT Statement.
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.
Module 5: Joining Multiple Tables. Overview Using Aliases for Table Names Combining Data from Multiple Tables Combining Multiple Result Sets.
4 Copyright © Oracle Corporation, All rights reserved. Displaying Data from Multiple Tables.
Retrieving Data Using the SQL SELECT Statement
SQL – join.
Boost your T-SQL with the APPLY Operator
Writing Basic SQL SELECT Statements
Basic select statement
02 | Advanced SELECT Statements
Sorting and Filtering Data
Querying Multiple Tables
Displaying Data from Multiple Tables
20761A 10: Using Subqueries Module 10   Using Subqueries.
Displaying Data from Multiple Tables
20761A 11: Using Set Operators Module 11   Using Set Operators.
03 | Querying Multiple Tables with Joins
CIS 336 PAPERS Lessons in Excellence-- cis336papers.com.
Sorting and Filtering Data
Writing Basic SQL SELECT Statements
20761B 12: Using Set Operators Module 12   Using Set Operators.
20761B 12: Using Set Operators Module 12   Using Set Operators.
Writing SELECT Queries
20761B 10: Using Subqueries Module 10   Using Subqueries.
Displaying Data from Multiple Tables Using Joins
JOINS (Joinining multiple tables)
Using Table Expressions
Writing Basic SQL SELECT Statements
Contents Preface I Introduction Lesson Objectives I-2
Displaying Data from Multiple Tables
Displaying Data from Multiple Tables
Manipulating Data Lesson 3.
JOINS (Joinining multiple tables)
Pivoting and Grouping Sets
Grouping and Aggregating Data
Presentation transcript:

Querying Multiple Tables Module 4 Consider reminding students how to use Object Explorer to browse the list of tables and their columns— they can then identify common columns to be used to join tables. Querying Multiple Tables

Querying with Cross Joins and Self Joins 20761B Module Overview 4: Querying Multiple Tables Querying with Cross Joins and Self Joins  

Lesson 1: Understanding Joins 20761B Lesson 1: Understanding Joins 4: Querying Multiple Tables Demonstration: Understanding Joins Question You have the following T-SQL query: SELECT o.ID AS OrderID, o.CustomerName, p.ProductName, p.ModelNumber, FROM Sales.Orders AS o JOIN Sales.Products AS p ON o.ProductID = p.ID; Which of the following types of join will the query perform? ( )Option 1: A cross join ( )Option 2: An inner join ( )Option 3: An outer left join ( )Option 4: An outer right join Answer (√) Option -2: An inner join

The FROM Clause and Virtual Tables 4: Querying Multiple Tables FROM clause determines source tables to be used in SELECT statement FROM clause can contain tables and operators Result set of FROM clause is virtual table Subsequent logical operations in SELECT statement consume this virtual table FROM clause can establish table aliases for use by subsequent phases of query On the whiteboard, consider drawing the relationship between input tables and the output virtual table.

SQL JOINS 20761B 4: Querying Multiple Tables On the whiteboard, consider drawing the relationship between input tables and the output virtual table.

Join Terminology: Cartesian Product 20761B Join Terminology: Cartesian Product 4: Querying Multiple Tables Characteristics of a Cartesian product Output or intermediate result of FROM clause Combine all possible combinations of two sets In T-SQL queries, usually not desired Special case: table of numbers For this topic, focus on the idea that a Cartesian product comes from joining two tables together without any regard to the relationships between them. Later in this module, we will cover the concept of a Cartesian product as the output of the first logical step in any join. Name Product Davis Alice Mutton Crab Meat Ipoh Coffee Funk King Name Davis Funk King Product Alice Mutton Crab Meat Ipoh Coffee

20761B Overview of Join Types 4: Querying Multiple Tables Join types in FROM clauses specify the operations performed on the virtual table: These join types will be explored in more detail in subsequent lessons in this module. Present this at overview level. Join Type Description Cross Combines all rows in both tables (creates Cartesian product) Inner Starts with Cartesian product; applies filter to match rows between tables based on predicate Outer Starts with Cartesian product; all rows from designated table preserved, matching rows from other table retrieved. Additional NULLs inserted as placeholders

T-SQL Syntax Choices ANSI SQL-92 ANSI SQL-89 20761B T-SQL Syntax Choices 4: Querying Multiple Tables ANSI SQL-92 Tables joined by JOIN operator in FROM Clause ANSI SQL-89 Tables joined by commas in FROM Clause Not recommended: accidental Cartesian products!   SELECT ... FROM Table1 JOIN Table2 ON <on_predicate> SELECT ... FROM Table1, Table2 WHERE <where_predicate>

Lesson 2: Querying with Inner Joins 20761B Lesson 2: Querying with Inner Joins 4: Querying Multiple Tables Demonstration: Querying with Inner Joins Question You have the following T-SQL query: SELECT HumanResources.Employees.ID, HumanResources.Employers.ID AS CompanyID, HumanResources.Employees.Name, HumanResources.Employers.Name AS CompanyName FROM HumanResources.Employees JOIN HumanResources.Employers ON HumanResources.Employees.EmployerID = HumanResources.Employers.ID; How can you improve the readability of this query? Answer Use AS to create more readable aliases for the Employees and Employers tables.

Understanding Inner Joins 20761B Understanding Inner Joins 4: Querying Multiple Tables Returns only rows where a match is found in both input tables Matches rows based on attributes supplied in predicate ON clause in SQL-92 syntax (preferred) WHERE clause in SQL-89 syntax Why filter in ON clause? Logical separation between filtering for purposes of join and filtering results in WHERE Typically no difference to query optimizer If join predicate operator is =, also known as equi-join Mention that an inner join is logically a Cartesian product followed by the application of a filter.

20761B Inner Join Syntax 4: Querying Multiple Tables List tables in FROM Clause separated by JOIN operator Table aliases preferred Table order does not matter   FROM t1 JOIN t2 ON t1.column = t2.column SELECT o.orderid, o.orderdate, od.productid, od.unitprice, od.qty FROM Sales.Orders AS o JOIN Sales.OrderDetails AS od ON o.orderid = od.orderid;

Join based on single matching attribute Inner Join Examples 4: Querying Multiple Tables Join based on single matching attribute Join based on multiple matching attributes (composite join) SELECT ... FROM Production.Categories AS C JOIN Production.Products AS P ON C.categoryid = P.categoryid;   -- List cities and countries where both -- customers and employees live SELECT DISTINCT e.city, e.country FROM Sales.Customers AS c JOIN HR.Employees AS e ON c.city = e.city AND c.country = e.country;

Lesson 3: Querying with Outer Joins 20761B Lesson 3: Querying with Outer Joins 4: Querying Multiple Tables Demonstration: Querying with Outer Joins Question You have a table named PoolCars and a table named Bookings in your ResourcesScheduling database. You want to return all the pool cars for which there are zero bookings. Which of the following queries should you use? ( )Option 1: SELECT pc.ID, pc.Make, pc.Model, pc.LicensePlate FROM ResourcesScheduling.PoolCars AS pc, ResourcesScheduling.Bookings AS b WHERE pc.ID = b.CarID; ( )Option 2: SELECT pc.ID, pc.Make, pc.Model, pc.LicensePlate FROM ResourcesScheduling.PoolCars AS pc RIGHT OUTER JOIN ResourcesScheduling.Bookings AS b ON pc.ID = b.CarID; ( )Option 3: SELECT pc.ID, pc.Make, pc.Model, pc.LicensePlate JOIN ResourcesScheduling.Bookings AS b ( )Option 4: SELECT pc.ID, pc.Make, pc.Model, pc.LicensePlate LEFT OUTER JOIN ResourcesScheduling.Bookings AS b ON pc.ID = b.CarID WHERE b.BookingID IS NULL; Answer (√) Option -2: SELECT pc.ID, pc.Make, pc.Model, pc.LicensePlate

Understanding Outer Joins 20761B Understanding Outer Joins 4: Querying Multiple Tables Returns all rows from one table and any matching rows from second table One table’s rows are “preserved” Designated with LEFT, RIGHT, FULL keyword All rows from preserved table output to result set Matches from other table retrieved Additional rows added to results for nonmatched rows NULLs added in places where attributes do not match Example: return all customers and, for those who have placed orders, return order information; customers without matching orders will display NULL for order details Consider explaining this as answering the "whether or not" question—all customers and their orders, whether or not they have an order.

20761B Outer Join Syntax 4: Querying Multiple Tables Return all rows from first table, only matches from second: Return all rows from second table, only matches from first: Return only rows from first table, with no match in second: FROM t1 LEFT OUTER JOIN t2 ON t1.col = t2.col Note that these are code fragments only, and cannot be run against the sample databases in this form. Point out the use of the NULL test in a WHERE clause (in the third example) to display only rows where no match exists. FROM t1 RIGHT OUTER JOIN t2 ON t1.col = t2.col FROM t1 LEFT OUTER JOIN t2 ON t1.col = t2.col WHERE t2.col IS NULL

Outer Join Examples All customers with order details if present: 20761B Outer Join Examples 4: Querying Multiple Tables All customers with order details if present: Customers who did not place orders: SELECT c.custid, c.contactname, o.orderid, o.orderdate FROM Sales.Customers AS C LEFT OUTER JOIN Sales.Orders AS O ON c.custid = o.custid;   SELECT c.custid, c.contactname, o.orderid, o.orderdate FROM Sales.Customers AS C LEFT OUTER JOIN Sales.Orders AS O ON c.custid = o.custid WHERE o.orderid IS NULL;

Lesson 4: Querying with Cross Joins and Self Joins 20761B Lesson 4: Querying with Cross Joins and Self Joins 4: Querying Multiple Tables Demonstration: Querying with Cross Joins and Self Joins Question You have two tables named FirstNames and LastNames. You want to generate a set of fictitious full names from this data. There are 150 entries in the FirstNames table and 250 entries in the LastNames table. You use the following query: SELECT (f.Name + ' ' + l.Name) AS FullName FROM FirstNames AS f CROSS JOIN LastNames AS l How many fictitious full names will be returned by this query? Answer 37,500 names

Understanding Cross Joins 20761B Understanding Cross Joins 4: Querying Multiple Tables Combine each row from first table with each row from second table All possible combinations output Logical foundation for inner and outer joins Inner join starts with Cartesian product, adds filter Outer join takes Cartesian output, filtered, adds back nonmatching rows (with NULL placeholders) Due to Cartesian product output, not typically a desired form of join Some useful exceptions: Table of numbers, generating data for testing  

No matching performed, no ON clause used 20761B Cross Join Syntax 4: Querying Multiple Tables No matching performed, no ON clause used Return all rows from left table combined with each row from right table (ANSI SQL-92 syntax): Return all rows from left table combined with each row from right table (ANSI SQL-89 syntax):   SELECT ... FROM t1 CROSS JOIN t2 SELECT ... FROM t1, t2

Create test data by returning all combinations of two inputs: Cross Join Examples 4: Querying Multiple Tables Create test data by returning all combinations of two inputs:   SELECT e1.firstname, e2.lastname FROM HR.Employees AS e1 CROSS JOIN HR.Employees AS e2;

Understanding Self Joins 20761B Understanding Self Joins 4: Querying Multiple Tables Why use self joins? Compare rows in same table to each other Create two instances of same table in FROM clause At least one alias required Example: Return all employees and the name of the employee’s manager While only one alias is required, it is useful to alias both tables in the join when demonstrating.

20761B Self Join Examples 4: Querying Multiple Tables Return all employees with ID of employee’s manager when a manager exists (inner join): Return all employees with ID of manager (outer join). This will return NULL for the CEO:   SELECT e.empid, e.lastname, e.title, e.mgrid, m.lastname FROM HR.Employees AS e JOIN HR.Employees AS m ON e.mgrid=m.empid; SELECT e. empid, e.lastname, e.title, m.mgrid FROM HR.Employees AS e LEFT OUTER JOIN HR.Employees AS m ON e.mgrid=m.empid;