Advanced Joins IN ( ) Expression Subqueries with IN ( ) Expression

Slides:



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

Multiple Table Queries
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.
Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320.
Populating and Querying tables Insert and mostly View (DML)
Northwind Sample database (also supplied with MS Access)
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 8 Advanced SQL.
Tutorial 5 Multi-table queries. Tutorial 5 objectives Displaying Data from Multiple Tables –[ ]Write SELECT statements to access data from more than one.
WRITING BASIC SQL SELECT STATEMENTS Lecture 7 1. Outlines  SQL SELECT statement  Capabilities of SELECT statements  Basic SELECT statement  Selecting.
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,
SQL in Action Amit Bhawnani & Nimesh Shah. Basic Structure SQL is based on set and relational operations with certain modifications and enhancements A.
SQL Review Tonga Institute of Higher Education. SQL Introduction SQL (Structured Query Language) a language that allows a developer to work with data.
Module 3: Retrieving Data. Overview Retrieving Data by Using the SELECT Statement Filtering Data Formatting Result Sets How Queries Are Processed Performance.
IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida Introduction to SQL—Topics Introduction to.
CpSc 3220 The Language of SQL The Language of SQL Chapters
CS146 References: ORACLE 9i PROGRAMMING A Primer Rajshekhar Sunderraman
IMS 4212: Data Manipulation 1 Dr. Lawrence West, MIS Dept., University of Central Florida Additional Data Manipulation Statements INSERT.
While you are waiting for class to start... (1)Login to SQL Server 2012 Management Studio (2) Execute the file called “SQLLab4.sql”. It is located on the.
More queries Outer joins and summary queries. Inner and outer joins An Inner join only returns matching rows from two tables –E.g. if I join the customer.
Query Lab CSC 240 Blum1. Log on to PMA (PHPMyAdmin) and click on the Northwind database CSC 240 Blum2.
© 2002 by Prentice Hall 1 Structured Query Language David M. Kroenke Database Concepts 1e Chapter 3 3.
# 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.
IMS 4212: Intro to Multi-Table SELECT Statements 1 Dr. Lawrence West, MIS Dept., University of Central Florida Multi-Table SELECT Statements—Topics.
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.
Simple Queries DBS301 – Week 1. Objectives Basic SELECT statement Computed columns Aliases Concatenation operator Use of DISTINCT to eliminate duplicates.
Copyright © 2016 Pearson Education, Inc. CHAPTER 7: ADVANCED SQL (PART I) Modern Database Management 12 th Edition Jeff Hoffer, Ramesh Venkataraman, Heikki.
Select Complex Queries Database Management Fundamentals LESSON 3.1b.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
Advanced SQL Advanced Database Dr. AlaaEddin Almabhouh.
COM621: Advanced Interactive Web Development Lecture 11 MySQL – Data Manipulation Language.
SQL SQL Ayshah I. Almugahwi Maryam J. Alkhalifa
Fundamentals of DBMS Notes-1.
CS3220 Web and Internet Programming More SQL
Rob Gleasure robgleasure.com
CpSc 3220 The Language of SQL
MySQL Subquery Source: Dev.MySql.com
Module 3: Retrieving Data
Chapter 12 Subqueries and MERGE Oracle 10g: SQL
02 | Advanced SELECT Statements
Database Systems: Design, Implementation, and Management Tenth Edition
Using the Set Operators
03 | Querying Multiple Tables with Joins
Writing Basic SQL SELECT Statements
Using the Set Operators
Structured Query Language (SQL) William Klingelsmith
Insert, Update, Delete Manipulating Data.
Web Services שפת SQL כתבה: זהבה יעקובסון ליווי מקצועי : ארז קלר
Restricting and Sorting Data
Chapter # 7 Introduction to Structured Query Language (SQL) Part II.
Chapter 2 Views.
Aggregations Various Aggregation Functions GROUP BY HAVING.
Rob Gleasure robgleasure.com
Structured Query Language
Using Subqueries to Solve Queries
Chapter 2 Views.
Structured Query Language – The Fundamentals
Contents Preface I Introduction Lesson Objectives I-2
CSC 453 Database Systems Lecture
Views Views CREATE VIEW AS Uses for Views.
CISB224 01A, 01B, 02A, 02B CCSB244 01A, 01B Semester I, 2007/2008
Rob Gleasure robgleasure.com
Rob Gleasure robgleasure.com
Using Subqueries to Solve Queries
Database Systems: Design, Implementation, and Management Tenth Edition
Topic 12 Lesson 2 – Retrieving Data with Queries
Using Subqueries to Solve Queries
Using the Set Operators
Subqueries Schedule: Timing Topic 25 minutes Lecture
Manipulating Data Lesson 3.
Presentation transcript:

Advanced Joins IN ( ) Expression Subqueries with IN ( ) Expression Left, Right, Full Outer Joins LEFT ( ), RIGHT ( ), LTRIM ( ), RTRIM ( ) Functions UNION Queries

The IN ( ) Expression The IN ( ) Expression can work like a simplified OR test in a WHERE clause Try these two queries SELECT * FROM Products WHERE SupplierID IN (28, 18, 27) WHERE SupplierID = 28 OR SupplierID = 18 OR SupplierID = 27

Try these three queries Subqueries with IN ( ) Try these three queries SELECT Products.* FROM Products INNER JOIN Suppliers ON Products.SupplierID = Suppliers.SupplierID WHERE Country = 'France' SELECT SupplierID FROM Suppliers SELECT * FROM Products WHERE SupplierID IN ( WHERE Country = 'France') Subquery

Subqueries with IN ( ) (cont.) Subqueries always execute first Subqueries may be nested Subqueries must return a single column Subquery return values must be compatible with those of the field being tested Compatible (same) value types SELECT * FROM Products WHERE SupplierID IN ( SELECT SupplierID FROM Suppliers WHERE Country = 'France') Single Column

Subquery Advantages—Efficiency How are the executions of these two queries different? Display all products purchased by customer 'Around the Horn' in 1997 using nested subqueries SELECT Products.* FROM Products INNER JOIN Suppliers ON Products.SupplierID = Suppliers.SupplierID WHERE Country = 'France' SELECT * FROM Products WHERE SupplierID IN ( SELECT SupplierID FROM Suppliers WHERE Country = 'France')

Subquery Advantages—Unary Relationships Do you remember this? Write the SQL to retrieve the name of Robert King's supervisor SELECT Sup.FirstName, Sup.LastName FROM Employees Emp INNER JOIN Employees Sup ON Emp.ReportsTo = Sup.EmployeeID WHERE Emp.LastName = 'King' AND Emp.FirstName = 'Robert'

Subquery Advantages—Unary Relationship (cont.) Rewrite as a subquery Use a subquery to find the names of all of the employees that Steven Buchanan supervises SELECT FirstName, LastName FROM Employees WHERE EmployeeID IN ( SELECT ReportsTo WHERE FirstName = 'Robert' AND LastName = 'King')

Subquery Advantages—No Direct Test Write a query to find the company names of all customers who placed orders in May of 1997 Hint: Use a Subquery Now write a query to find the company names of all customers who did not place an order in May of 1997 SELECT CompanyName FROM Customers WHERE CustomerID IN ( SELECT DISTINCT CustomerID FROM Orders WHERE DatePart(mm, OrderDate) = 5 AND DatePart(yy, OrderDate) = 1997)

Subquery Advantages—No Direct Test (cont.) Write a query to list the names of all products that are not discontinued that were not sold during May of 1997

Left (and Right) Outer Joins You will often want to list all records in one table as well as related records in a second, even if there are no related records in the second table Execute the following query Write a query to show all category names along with matching product names How can we get our new category to show? INSERT INTO Categories ( CategoryName, Description) VALUES('Test Category', 'An artificial category added for testing')

Left (and Right) Outer Joins (cont.) SELECT CategoryName, ProductName FROM Categories LEFT JOIN Products ON Categories.CategoryID = Products.CategoryID The query above returns all category names and matching product names if there is a matching product When there is no matching product a Null is returned All Category records are returned because Categories is on the Left in the LEFT JOIN expression Right JOIN would reverse the logic

Left (and Right) Outer Joins (cont.) Run these two queries—What's wrong here? SELECT CompanyName, OrderDate FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID ORDER BY CompanyName, OrderDate WHERE DatePart(mm, OrderDate) = 5 AND DatePart(yy, OrderDate) = 1997

Left (and Right) Outer Joins (cont.) Where clause type filters must be applied in a special way in outer joins Add the row-limiting criteria expressions as part of the join criteria Write a query to list all Employees along with orders they made in 1998 SELECT CompanyName, OrderDate FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID AND DatePart(mm, OrderDate) = 5 AND DatePart(yy, OrderDate) = 1997 ORDER BY CompanyName, OrderDate

The Full Outer Join SELECT Emp.LastName AS 'Emp Last', Emp.FirstName AS 'Emp First', Sup.LastName AS 'Sup Last', Sup.FirstName AS 'Sup First' FROM Employees Emp FULL JOIN Employees Sup ON Emp.ReportsTo = Sup.EmployeeID

Functions of the Day LEFT ( ) and RIGHT ( ) return a specified number of characters from the left or right sides of a string SELECT FirstName, Left(FirstName, 1) + '.' AS 'Initial' FROM Employees

Functions of the Day (cont.) LTRIM and RTRIM remove Leading/Trailing spaces from a string When did I need to use this SQL? UPDATE LastName SET LastName = LTRIM(LastName)

Union Queries A Union Query allows you to append the results of two different queries and return them as two result sets Try this: SELECT CAST(SupplierID AS char(10)) AS 'ID', CompanyName, 'Supplier' AS 'Type' FROM Suppliers UNION SELECT CAST(CustomerID AS char(10)) AS 'ID', CompanyName, 'Customer' AS 'Type' FROM Customers

UNION Queries (cont.) All components queries of a Union query must return: The same number of columns Compatible column data types Use CAST function when necessary The same column names Use AS to rename columns when necessary UNION is particularly useful when combining current and archived (or other partitioned) data into one result set Write a query to return the names of all people in the Northwinds DB along with their phone numbers