Define terms Write single and multiple table SQL queries Write noncorrelated and correlated subqueries Define and use three types of joins



Similar documents
Chapter 9 Joining Data from Multiple Tables. Oracle 10g: SQL

Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification

Join Example. Join Example Cart Prod Comprehensive Consulting Solutions, Inc.All rights reserved.

Using SQL Queries to Insert, Update, Delete, and View Data: Joining Multiple Tables. Lesson C Objectives. Joining Multiple Tables

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff

Lab # 5. Retreiving Data from Multiple Tables. Eng. Alaa O Shama

Oracle Database 12c: Introduction to SQL Ed 1.1

MOC 20461C: Querying Microsoft SQL Server. Course Overview

Relational Databases

Relational Database: Additional Operations on Relations; SQL

Where? Originating Table Employees Departments

1 Structured Query Language: Again. 2 Joining Tables

Displaying Data from Multiple Tables

COMP 5138 Relational Database Management Systems. Week 5 : Basic SQL. Today s Agenda. Overview. Basic SQL Queries. Joins Queries

GET DATA FROM MULTIPLE TABLES QUESTIONS

Introducing Microsoft SQL Server 2012 Getting Started with SQL Server Management Studio

Querying Microsoft SQL Server

Advanced SQL. Lecture 3. Outline. Unions, intersections, differences Subqueries, Aggregations, NULLs Modifying databases, Indexes, Views

Chapter 5. SQL: Queries, Constraints, Triggers

Querying Microsoft SQL Server 2012

Oracle SQL. Course Summary. Duration. Objectives

SQL Programming. Student Workbook

Course ID#: W 35 Hrs. Course Content

Course 10774A: Querying Microsoft SQL Server 2012

Course 10774A: Querying Microsoft SQL Server 2012 Length: 5 Days Published: May 25, 2012 Language(s): English Audience(s): IT Professionals

In this Lecture SQL SELECT. Example Tables. SQL SELECT Overview. WHERE Clauses. DISTINCT and ALL SQL SELECT. For more information

Querying Microsoft SQL Server 20461C; 5 days

Displaying Data from Multiple Tables. Copyright 2004, Oracle. All rights reserved.

Displaying Data from Multiple Tables. Copyright 2006, Oracle. All rights reserved.

Effective Use of SQL in SAS Programming

Querying Microsoft SQL Server Course M Day(s) 30:00 Hours

Displaying Data from Multiple Tables. Copyright 2004, Oracle. All rights reserved.

Instant SQL Programming

ICAB4136B Use structured query language to create database structures and manipulate data

Oracle 10g PL/SQL Training

SQL SUBQUERIES: Usage in Clinical Programming. Pavan Vemuri, PPD, Morrisville, NC

MOC QUERYING MICROSOFT SQL SERVER

D61830GC30. MySQL for Developers. Summary. Introduction. Prerequisites. At Course completion After completing this course, students will be able to:

Lecture Slides 4. SQL Summary. presented by Timothy Heron. Indexes. Creating an index. Mathematical functions, for single values and groups of values.

Relational Division and SQL

Database Programming with PL/SQL: Learning Objectives

Advanced SQL - Subqueries and Complex Joins

Introduction to Microsoft Jet SQL

SQL Server for developers. murach's TRAINING & REFERENCE. Bryan Syverson. Mike Murach & Associates, Inc. Joel Murach

Triggers & Packages. {INSERT [OR] UPDATE [OR] DELETE}: This specifies the DML operation.

Introduction to Querying & Reporting with SQL Server

Course 20461C: Querying Microsoft SQL Server Duration: 35 hours

Databases 2011 The Relational Model and SQL

Database CIS 340. lab#6. I.Arwa Najdi

SQL SELECT Query: Intermediate

2874CD1EssentialSQL.qxd 6/25/01 3:06 PM Page 1 Essential SQL Copyright 2001 SYBEX, Inc., Alameda, CA

CHAPTER 12. SQL Joins. Exam Objectives

RDBMS Using Oracle. Lecture Week 7 Introduction to Oracle 9i SQL Last Lecture. kamran.munir@gmail.com. Joining Tables

WRITING EFFICIENT SQL. By Selene Bainum

Execution Strategies for SQL Subqueries

Business Systems Analysis Certificate Program. Millennium Communications & Training Inc. 2013, All rights reserved

The Relational Algebra

Information Systems SQL. Nikolaj Popov

Database Query 1: SQL Basics

Querying Microsoft SQL Server 2012

Schema Mappings and Data Exchange

A basic create statement for a simple student table would look like the following.

Data Structure: Relational Model. Programming Interface: JDBC/ODBC. SQL Queries: The Basic From

Databases in Engineering / Lab-1 (MS-Access/SQL)

Oracle Database: SQL and PL/SQL Fundamentals

Querying Microsoft SQL Server (20461) H8N61S

Oracle Database: SQL and PL/SQL Fundamentals

SQL Query Evaluation. Winter Lecture 23

4. SQL. Contents. Example Database. CUSTOMERS(FName, LName, CAddress, Account) PRODUCTS(Prodname, Category) SUPPLIERS(SName, SAddress, Chain)

SQL: Queries, Programming, Triggers

Question 1. Relational Data Model [17 marks] Question 2. SQL and Relational Algebra [31 marks]

5.1 Database Schema Schema Generation in SQL

Structured Query Language (SQL)

Example Instances. SQL: Queries, Programming, Triggers. Conceptual Evaluation Strategy. Basic SQL Query. A Note on Range Variables

Unit 3. Retrieving Data from Multiple Tables

Programming with SQL

The process of database development. Logical model: relational DBMS. Relation

SQL: Queries, Programming, Triggers

Querying Microsoft SQL Server 2012

SQL NULL s, Constraints, Triggers

Analyzing Data HPE Vertica Analytic Database. Software Version: 7.2.x

More on SQL. Juliana Freire. Some slides adapted from J. Ullman, L. Delcambre, R. Ramakrishnan, G. Lindstrom and Silberschatz, Korth and Sudarshan

Course -Oracle 10g SQL (Exam Code IZ0-047) Session number Module Topics 1 Retrieving Data Using the SQL SELECT Statement

Querying Microsoft SQL Server Querying Microsoft SQL Server D. Course 10774A: Course Det ails. Co urse Outline

The join operation allows you to combine related rows of data found in two tables into a single result set.

Examine the structure of the EMPLOYEES table: EMPLOYEE_ID NUMBER Primary Key FIRST_NAME VARCHAR2(25) LAST_NAME VARCHAR2(25)

Performing Queries Using PROC SQL (1)

Oracle Database: SQL and PL/SQL Fundamentals NEW

Writing Control Structures

MySQL for Beginners Ed 3

Introduction to SQL and SQL in R. LISA Short Courses Xinran Hu

Introduction to SQL C H A P T E R3. Exercises

Lecture 4: More SQL and Relational Algebra

Using Temporary Tables to Improve Performance for SQL Data Services

Introduction to database design

Boats bid bname color 101 Interlake blue 102 Interlake red 103 Clipper green 104 Marine red. Figure 1: Instances of Sailors, Boats and Reserves

Retrieval: Multiple Tables and Aggregation

SQL Server. 1. What is RDBMS?

Guide to Performance and Tuning: Query Performance and Sampled Selectivity

DBMS / Business Intelligence, SQL Server

Transcription:

Chapter 7 Advanced SQL 1 Define terms Objectives Write single and multiple table SQL queries Write noncorrelated and correlated subqueries Define and use three types of joins 2

Nested Queries (Subqueries) Subquery: Placing an inner query (SELECT statement) inside an outer query Can be used in place of a table name, or an expression that returns a list, for operators that accept a list (IN, EXISTS, =ANY, etc.) Subqueries can be: Noncorrelated executed once for the entire outer query Correlated executed once for each row returned by the outer query 3 Subquery Example Show all customers who have placed an order The IN operator will test to see if the CUSTOMER_ID value of a row is included in the list returned from the subquery Subquery is embedded in parentheses. In this case it returns a list that will be used in the WHERE clause of the outer query 4

Set Membership: Existential Show all faculty who qualified to teach some course before 10/30/2010. SELECT FacultyID, FacultyName FROM Faculty_T WHERE FacultyID IN ( SELECT DISTINCT FacultyID FROM Qualified_T WHERE DateQualified < 2010-10-30 ); FROM Qualified T Existential: ti Easy!! Subquery returns the IDs of all faculty who qualified to teach some course before 10/30/2010 5 Set Membership: Universal Show all faculty who got all their qualifications before 10/30/2010. Universal: Hard! 6

Set Membership: Universal Find the other faculty, who got some qualification after 10/30/2010. SELECT FacultyName FROM Faculty_T WHERE FacultyID IN ( SELECT DISTINCT FacultyID FROM Qualified_T WHERE DateQualified >= 2010-10-30 ); Find all faculty who got all qualifications before 10/30/2010. SELECT FacultyName FROM Faculty_T WHERE FacultyID NOT IN ( SELECT DISTINCT FacultyID FROM Qualified_T WHERE DateQualified >= 2010-10-30 ); 7 Figure 7-7a Processing a noncorrelated subquery A noncorrelated subquery processes completely before the outer query begins 8

Correlated vs. Noncorrelated Subqueries Noncorrelated subqueries: Do not depend on data from the outer query Execute once for the entire outer query Correlated subqueries: Mk Make use of fdt data from the outer query Execute once for each row of the outer query Can use the EXISTS operator 9 Correlated Subquery Example Show all courses offered in the first semester of 2008. The EXISTS operator will return a TRUE value if the subquery resulted in a non-empty set, otherwise it returns a FALSE SELECT DISTINCT CourseName FROM Course_T WHERE EXISTS (SELECT * FROM Section_T WHERE CourseID = Course_T.CourseID AND Semester = I-2008 ); The subquery is testing for a value that comes from the outer query A correlated subquery always refers to an attribute from a table referenced in the outer query 10

Correlated Subquery Example Show all courses offered in the first semester of 2008. SELECT DISTINCT CourseName FROM Course_T WHERE EXISTS (SELECT * FROM Section_T WHERE CourseID = Course_T.CourseID AND Semester = I-2008 ); 1. The first CourseID is selected from Course_T (ISM 3113). 2. The subquery is evaluated to see if any sections exist for semester I-2008. EXISTS is valued as TRUE and the CourseName is added to the results table. 3. The next CourseID is selected from Course_T (ISM 3112), etc. 11 NULLs in SQL Whenever we don t have a value, we can use a NULL Can mean many things Value does not exist Value exists but is unknown Value not applicable How does SQL cope with tables that have NULLs? 12

NULL Values If x = NULL then 4*(3-x)/7 is still NULL If x = NULL then x > 6 is UNKNOWN In SQL there are three boolean values: FALSE = 0 UNKNOWN = 0.5 TRUE = 1 C1 AND C2 = min(c1, C2) C1 OR C2 = max(c1, C2) NOT C1 = 1 - C1 SELECT * FROM Person WHERE (age < 25) AND (height > 6 OR weight > 190); Rule in SQL: include only records that yields TRUE. 13 Unexpected behavior: SELECT * FROM Person WHERE (age < 25) OR (age >= 25); NULL Values Some Persons not included! Can test for NULL explicitly: SELECT * FROM Person WHERE (age < 25) OR (age >= 25) OR (age IS NULL); 14

Quick Note: GROUP-BY vs. Subquery Find students who take >= 2 classes Attempt 1 (with subqueries): SELECT StudentName FROM Student_T WHERE (SELECT COUNT(*) FROM (SELECT R.StudentID FROM Registration_T AS R, Student_T AS S WHERE S.StudentID = R.StudentID) AS CT )>=2; This is SQL by a novice 15 Quick Note (contd.) Find students who take >= 2 classes Attempt 2 (with GROUP BY): SELECT StudentName FROM Student_T AS S, Registration_T AS R WHERE S.StudentID = R.StudentID GROUP BY S.StudentID HAVING COUNT(R.SectionNo) >= 2; This is SQL by an expert 16

Union Queries Combine the output (union of multiple queries) together into a single result table First query Combine Second query 17 Figure 7-8 Combining queries using UNION Note: with UNION queries, the quantity and data types of the attributes in the SELECT clauses of both queries es must be identical 18

Processing Multiple Tables Joins Join Cartesian product of two tables (which gets us all pairs of rows, with one coming from each table) followed by a selection process according to some predicate. pedcae. Implicit Join two or more tables appear in the FROM clause, separated by commas; the join condition (that is, the predicate that decides which rows match) is added to the WHERE clause. 19 Implicit Join Example For each student registered in the first semester of 2008, what is the student name and ID? SELECT DISTINCT FROM WHERE S.StudentID, StudentName Student_T AS S, Registration_T AS R S.StudentID = R.StudentID; Join between Student_T and Registration_T 20

Explicit Join For each student registered in the first semester of 2008, what is the student name and ID? SELECT DISTINCT FROM S.StudentID, StudentName Student_T S JOIN Registration_T R ON (S.StudentID = R.StudentID); Selection Condition 21 Natural Join Most join conditions involve the equality predicate. SQL supports the concept of a NATURAL JOIN, which is a join in which the join condition is created implicitly, by requiring equality of all fields with the same name in both tables. SELECT DISTINCT StudentID, StudentName FROM Student_T NATURAL JOIN Registration_T; StudentID is a field common to both tables. Only registered students will be listed. 22

Natural Join and USING Natural joins are too brittle. SQL also supports a much better JOIN... USING syntax. Rather than writing ON and the join condition, we write USING and then a list of fields which must match. SELECT FROM StudentID, StudentName Student_T JOIN Registration_T USING (StudentID); 23 Natural Join Flaw Natural joins in SQL are inner joins (a.k.a equi-joins), meaning that rows must have matching values to appear in the result table. SELECT FROM StudentID, StudentName Student_T JOIN Registration_T USING (StudentID); /* Students who never registered will be lost */ Many times we want all rows from a certain table appear in a join, even when there is no corresponding join on the other table. This can be achieved with an OUTER JOIN. 24

Outer Joins Joins in which rows with no matching values in common columns are nonetheless thl included lddin the result lttbl table o Left Outer Join: Include the left tuple even if there is no match o Right Outer Join: Include the right tuple even if there is no match o Full Outer join: Include both left and right tuple even if there is no match 25 Outer Join Example List the student ID, name and registration information for each student. Include students even if not yet registered. SELECT * FROM Student_T S LEFT OUTER JOIN Registration_T R ON (S.StudentID = R.StudentID); All students will appear in the results table. Note: Same principles apply to more than two tables involved din a JOIN operation. 26

Multiple Table Join Example Assemble all llinformation i necessary to create an invoice i for order number 1006 Four tables involved in this join Each pair of tables requires an equality-check condition in the WHERE clause, matching primary keys against foreign keys 27 Figure 7-4 Results from a four-table join (edited for readability) From CUSTOMER_T table From ORDER_T table From PRODUCT_T table 28

Self-Join Example The same table is used on both sides of the join; distinguished using table aliases Slfji Self-joins are usually used on tables with ihunary relationships 29