Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320.

Slides:



Advertisements
Similar presentations
Advanced SQL Topics Edward Wu.
Advertisements

Advanced SQL (part 1) CS263 Lecture 7.
© Abdou Illia MIS Spring 2014
© 2007 by Prentice Hall (Hoffer, Prescott & McFadden) 1 Joins and Sub-queries in SQL.
Join Queries CS 146. Introduction: Join Queries So far, our SELECT queries have retrieved data from a single table Usually queries combine data from multiple.
Chapter 4 Joining Multiple Tables
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.
Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 1 Modern Database Management 11 th Edition Jeffrey A. Hoffer, V. Ramesh, Heikki Topi.
Action Queries CS 320. Review: SQL Command Types  Data Definition Language (DDL)  Used to create and modify database objects  Data Manipulation Language.
Chapter Information Systems Database Management.
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.
Introduction to Structured Query Language (SQL)
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 8 Advanced SQL.
View Sen Zhang. Views are very common in business systems users view of data is simplified a form of security - user sees only the data he/she needs to.
Slides adapted from A. Silberschatz et al. Database System Concepts, 5th Ed. SQL - part 2 - Database Management Systems I Alex Coman, Winter 2006.
Introduction to Structured Query Language (SQL)
Creating Database Tables CS 320. Review: Levels of data models 1. Conceptual: describes WHAT data the system contains 2. Logical: describes HOW the database.
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.
Copyright 2007, Paradigm Publishing Inc. BACKNEXTEND 3-1 LINKS TO OBJECTIVES Save a Filter as a Query Save a Filter as a Query Parameter Query Inner, Left,
ITBIS373 Database Development
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.
CSC271 Database Systems Lecture # 12. Summary: Previous Lecture  Row selection using WHERE clause  WHERE clause and search conditions  Sorting results.
INTRODUCTION TO DATABASES CS 260 Database Systems.
Structure Query Language SQL. Database Terminology Employee ID 3 3 Last name Small First name Tony 5 5 Smith James
Single-Table Queries 1: Basics CS 320 Online. Review: SQL Command Types  Data Definition Language (DDL)  Used to create and modify database objects.
Joins & Sub-queries. Oracle recognizes that you may want data that resides in multiple tables drawn together in some meaningful way. One of the most important.
Database Design 1: Introduction and Terminology CS 320.
ADVANCED SQL SELECT QUERIES CS 260 Database Systems.
SQL SELECT QUERIES CS 260 Database Systems. Overview  Introduction to SQL  Single-table select queries  Using the DBMS to manipulate data output 
® Microsoft Access 2010 Tutorial 9 Using Action Queries and Advanced Table Relationships.
Creating PHPs to Insert, Update, and Delete Data CS 320.
M1G Introduction to Database Development 5. Doing more with queries.
XP Chapter 3 Succeeding in Business with Microsoft Office Access 2003: A Problem-Solving Approach 1 Analyzing Data For Effective Decision Making Chapter.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Tutorial 9 Using Action Queries and Advanced Table Relationships.
Access 2007 ® Use Databases How can Microsoft Access 2007 help you structure your database?
Microsoft Access 2013 ®® Tutorial 9 Using Action Queries and Advanced Table Relationships.
Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.
Introduction to Databases Queries CS 146. Sample Database: CANDY_CUSTOMER CANDY_PURCHASE CANDY_CUST_TYPE CANDY_PRODUCT.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
Multiple Table Queries 1: Inner Joins CS 320. Introduction: Join Queries Usually queries combine data from multiple tables:  List how much (pounds) of.
SQL ACTION QUERIES AND TRANSACTION CONTROL CS 260 Database Systems.
DATA NORMALIZATION CS 260 Database Systems. Overview  Introduction  Anomalies  Functional dependence  Normal forms  1NF  2NF  3NF  BCNF  Denormalization.
Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,
# 1# 1 QueriesQueries How do we ask questions of the data? What is SELECT? What is FROM? What is WHERE? What is a calculated field? Spring 2010 CS105.
In this session, you will learn to: Query data by using joins Query data by using subqueries Objectives.
Database Design 4: Deriving Tables From Data Models CS 320.
IMS 4212: Intro to Multi-Table SELECT Statements 1 Dr. Lawrence West, MIS Dept., University of Central Florida Multi-Table SELECT Statements—Topics.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
Join Queries CS 146. Introduction: Join Queries  So far, our SELECT queries have retrieved data from a single table  Usually queries combine data from.
MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Sravanthi Lakkimsety Mar 14,2016.
Copyright © 2016 Pearson Education, Inc. CHAPTER 7: ADVANCED SQL (PART I) Modern Database Management 12 th Edition Jeff Hoffer, Ramesh Venkataraman, Heikki.
CSC314 DAY 9 Intermediate SQL 1. Chapter 6 © 2013 Pearson Education, Inc. Publishing as Prentice Hall USING AND DEFINING VIEWS  Views provide users controlled.
Introduction to Databases Queries CS 146. Sample Database: CANDY_CUSTOMER CANDY_PURCHASE CANDY_CUST_TYPE CANDY_PRODUCT.
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.
Dr. Chen, Oracle Database System (Oracle) 1 Basic Nested Queries and Views Jason C. H. Chen, Ph.D. Professor of MIS School of Business Gonzaga University.
MySQL Subquery Source: Dev.MySql.com
Prepared by : Moshira M. Ali CS490 Coordinator Arab Open University
Subqueries Schedule: Timing Topic 25 minutes Lecture
Basic Nested Queries and Views
Writing Correlated Subqueries
Relational Queries (query 12) Display vendor contact info (contact person and phone number) for inventory products (relationship query) Query: Inventory.
Creating and Maintaining
SQL Subquery.
Contents Preface I Introduction Lesson Objectives I-2
Subqueries Schedule: Timing Topic 25 minutes Lecture
Advanced Joins IN ( ) Expression Subqueries with IN ( ) Expression
Subqueries Schedule: Timing Topic 25 minutes Lecture
Subqueries Schedule: Timing Topic 25 minutes Lecture
Tutorial 9 Using Action Queries and Advanced Table Relationships
Presentation transcript:

Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320

Review: Inner Join Queries Retrieve records from multiple tables Tables must have links through primary key/foreign key relationships

Problem: What if you want to create a query that retrieves records from two tables even if all of the records don't have matching records in a joined table? Example: Create a query that retrieves the customer ID and name of every customer, along with the purchase dates of all of the customer’s purchases. Do not retrieve duplicate records, and order the values by customer ID.  Problem: some customers have not made purchases! SELECT DISTINCT cust.cust_id, cust_name, purch_date FROM candy_customer cust JOIN candy_purchase purch ON cust.cust_id = purch.cust_id ORDER BY cust.cust_id;

Solution: Create an Outer Join Retrieves all of the records from one table, and also retrieves the matching columns from a second table  Retrieves the records in the first table even if they don’t have matching records in the second table Types of outer joins:  Left  Right  Full (not supported by MySQL)

Left Outer Join Retrieves all of the records in the left (first) table, along with matching records in the right (second) table, if they exist General syntax: SELECT field1, field2, … FROM Table1 LEFT OUTER JOIN Table2 ON join_condition WHERE search_condition(s); NOTE: the word "OUTER" is optional

Left Outer Join Example SELECT DISTINCT c.cust_id, cust_name, purch_date FROM candy_customer c LEFT JOIN candy_purchase p ON c.cust_id = p.cust_id ORDER BY c.cust_id

Right Outer Join Retrieves all of the records in the right (second) table, along with matching records in the left (first) table, if they exist General syntax: SELECT field1, field2, … FROM table_1 RIGHT JOIN table_2 ON join_condition WHERE search_condition(s);

Self Joins Join the table to itself using a table alias ACME_EMPLOYEE Employee_ID Employee_First_Name Employee_Last_Name Employee_DOB SupervisorID (FK) SELECT emp.employee_last_name AS employee, sup.employee_last_name AS supervisor FROM acme_employee emp JOIN acme_employee sup ON emp.supervisor_id = sup.employee_id; Employee_ ID Employee_ First_ Name Employe_ Last_ Name Employee_ DOB Supervisor_ ID 1MarySmith7/14/1968 2JohnJones2/19/ JasonSwift11/28/19751

Self Joins Employee_ ID Employee_ First_ Name Employe_ Last_ Name Employee_ DOB Supervisor_ ID 1MarySmith7/14/1968 2JohnJones2/19/ JasonSwift11/28/19751 EMP alias Employee_ ID Employee_ First_ Name Employe_ Last_ Name Employee_ DOB Supervisor_ ID 1MarySmith7/14/1968 2JohnJones2/19/ JasonSwift11/28/19751 SUP alias SELECT emp.employee_last_name AS employee, sup.employee_last_name AS supervisor FROM acme_employee emp JOIN acme_employee sup ON emp.supervisor_id = sup.employee_id;

Consist of a main query and a subquery Subquery retrieves a search condition value for the main query Uses  Alternative way to retrieve data from one table based on a search condition from another table  Sometimes it's the only way you can retrieve the data you need Nested Queries

Nested Query Syntax SELECT purch_id, purch_date, purch_pounds FROM candy_purchase WHERE prod_id = (SELECT prod_id FROM candy_product WHERE prod_desc = 'Celestial Cashew Crunch')

The subquery returns exactly ONE value The SearchColumn in the main query MUST MATCH the SearchColumn in the subquery The SearchColumn is usually a foreign key value Nested Query Example Notes SELECT purch_id, purch_date, purch_pounds FROM candy_purchase WHERE prod_id = (SELECT prod_id FROM candy_product WHERE prod_desc = 'Celestial Cashew Crunch')

Use if the subquery might retrieve multiple values Alternate Nested Query Syntax SELECT cust_id, purch_id, purch_date, purch_pounds FROM candy_purchase WHERE cust_id IN (SELECT cust_id FROM candy_customer WHERE cust_type = 'P')

The main query in a nested query can have multiple search conditions whose values are specified by separate subqueries: Nested Queries with Multiple Subqueries SELECT purch_id, purch_date FROM candy_purchase WHERE prod_id = (SELECT prod_id FROM candy_product WHERE prod_desc = 'Celestial Cashew Crunch') AND cust_id IN (SELECT cust_id FROM candy_customer WHERE cust_type = 'P')

SELECT prod_desc FROM candy_product WHERE prod_id IN (SELECT prod_id FROM candy_purchase WHERE purch_date = ' ' AND cust_id IN (SELECT cust_id FROM candy_customer WHERE cust_type = 'P')) A subquery can also be a nested query:  Note positions of the nesting parentheses Nested Subqueries

For many nested queries, you could achieve the same result with a join query  Nested may seem more straight-forward than the equivalent join query  Downside: Executes more slowly Final result can only come from the main query table Some nested query results can’t be retrieved through a join Notes on Using Nested Queries

Query requiring a nested query: Create a query that retrieves the IDs of all customers whose average purchase amount is greater than the average pounds of all customers' purchases SELECT cust_id, AVG(purch_pounds) FROM candy_purchase GROUP BY cust_id HAVING AVG(purch_pounds) > (SELECT AVG(purch_pounds) FROM candy_purchase);

Create and debug the subquery(ies) first, then add the main query If the main query doesn’t run, debug it by hard-coding the search condition rather than using the subquery Strategy for Creating and Debugging Nested Queries

Views Virtual table based on a query  You can think of it as a stored query Purposes:  Controls the fields that certain users can access  Provides a way to simplify join queries

Types of Views Simple view: based on a single table  Primary use: hides fields to control access  Users can select, insert, update, and delete from simple views just as with tables CREATE OR REPLACE VIEW candy_customer_view AS SELECT cust_id, cust_name, cust_type, cust_addr,cust_zip FROM candy_customer;

Types of Views Complex view: created by joining multiple tables  Primary use: to simplify queries  Users can select from complex views  Users CANNOT insert, update, and delete from complex views CREATE OR REPLACE VIEW purchases_view AS SELECT cust_name, purch_date, purch_delivery_date, prod_desc, purch_pounds FROM candy_purchase purch INNER JOIN candy_product prod ON purch.prod_id = prod.prod_id JOIN candy_customer cust ON cust.cust_id = purch.cust_id;

Test Yourself: You need to retrieve the description of all candy products, along with the purchase date and pounds purchased. You need to create a(n) _________ query. a. Inner join b. Outer join c. Nested d. View e. None of the above

Test Yourself: You need to retrieve the description of all candy products, along with the purchase date and pounds purchased. You need to create a(n) _________ query. a. Inner join b. Outer join c. Nested d. View e. None of the above

Test Yourself: How many records does the following query retrieve? a. 9 b. 14 c. 7 d. None of the above SELECT DISTINCT c.cust_id, cust_name, purch_date FROM candy_customer c RIGHT JOIN candy_purchase p ON c.cust_id = p.cust_id ORDER BY c.cust_id

Test Yourself: How many records does the following query retrieve? a. 9 b. 14 c. 7 d. None of the above SELECT DISTINCT c.cust_id, cust_name, purch_date FROM candy_customer c RIGHT JOIN candy_purchase p ON c.cust_id = p.cust_id ORDER BY c.cust_id