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.

Slides:



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

Sometimes you need to use data from more than one table. In example1, the report displays data from two separate tables. Employee IDs exist in the EMPLOYEES.
© 2007 by Prentice Hall (Hoffer, Prescott & McFadden) 1 Joins and Sub-queries in SQL.
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.
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.
5 Copyright © 2004, Oracle. All rights reserved. Displaying Data from Multiple Tables.
Introduction to Structured Query Language (SQL)
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.
Objectives After completing this lesson, you should be able to do the following: Write SELECT statements to access data from more than one table using.
Learningcomputer.com SQL Server 2008 – Entity Relationships in a Database.
Component 4/Unit 6f Topic VI: Create simple querying statements for the database The SELECT statement Clauses Functions Joins Subqueries Data manipulation.
Chapter 9 Joining Data from Multiple Tables
SQL advanced select using Oracle 1 7. Multiple Tables: Joins and Set Operations 8. Subqueries: Nested Queries.
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.
1 Agenda – 03/25/2014 Login to SQL Server 2012 Management Studio. Answer questions about HW#7 – display answers. Exam is 4/1/2014. It will be in the lab.
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.
One-to-many relationship Relational databases link several entities based on relationships that exist (based on modeling reality) 1:m relationship example:
Agenda for 02/21/2006 Learn how to use more than one table in a query. Discuss how DBMS processes multiple tables. Explain the different types of joins.
1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement.
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.
Join, Subqueries and set operators. Obtaining Data from Multiple Tables EMPLOYEES DEPARTMENTS … …
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
1 Chapter 10 Joins and Subqueries. 2 Joins & Subqueries Joins – Methods to combine data from multiple tables – Optimizer information can be limited based.
Agenda for 02/16/2006 Answer any questions about SQL project. Do you want to see any of the answers for the queries? Discuss additional formatting options.
5 Copyright © 2004, Oracle. All rights reserved. Displaying Data from Multiple Tables.
While you are waiting for class to start... (1) Login to SQL Server 2012 Management Studio (2) Execute the file called “SQLLab3.sql”. It is located on.
Chapter 7: advanced sql Jeffrey A. Hoffer, V. Ramesh, Heikki Topi
SQL advanced select using Oracle 1. 2 Select Simple –data from a single table Advanced –data from more tables join sub-queries.
Chapter 12 Subqueries and Merge Statements
A Guide to SQL, Eighth Edition Chapter Five Multiple-Table Queries.
6 Copyright © 2007, Oracle. All rights reserved. Retrieving Data Using Subqueries.
Component 4: Introduction to Information and Computer Science Unit 6: Databases and SQL Lecture 6 This material was developed by Oregon Health & Science.
# 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.
Agenda for Class - 03/04/2014 Answer questions about HW#5 and HW#6 Review query syntax. Discuss group functions and summary output with the GROUP BY statement.
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.
Database Programming Sections 6 –Subqueries, Single Row Subqueries, Multiple-row Subqueries, Correlated Subqueries.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Sravanthi Lakkimsety Mar 14,2016.
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.
 MySQL  DDL ◦ Create ◦ Alter  DML ◦ Insert ◦ Select ◦ Update ◦ Delete  DDL(again) ◦ Drop ◦ Truncate.
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.
Advanced SQL Advanced Database Dr. AlaaEddin Almabhouh.
Using Subqueries to Solve Queries
Chapter 12 Subqueries and MERGE Oracle 10g: SQL
Oracle Join Syntax.
Displaying Data from Multiple Tables
Subqueries.
Subqueries Schedule: Timing Topic 25 minutes Lecture
Displaying Data from Multiple Tables
Displaying Data from Multiple Tables
03 | Querying Multiple Tables with Joins
Using Subqueries to Solve Queries
Writing Correlated Subqueries
Structured Query Language (SQL) William Klingelsmith
Displaying Data from Multiple Tables Using Joins
Oracle Join Syntax.
Using Subqueries to Solve Queries
Subqueries Schedule: Timing Topic 25 minutes Lecture
Oracle Join Syntax.
Using Subqueries to Solve Queries
Displaying Data from Multiple Tables
Using Subqueries to Solve Queries
Displaying Data from Multiple Tables
Subqueries Schedule: Timing Topic 25 minutes Lecture
Subqueries Schedule: Timing Topic 25 minutes Lecture
Presentation transcript:

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 k: drive in the IS475\LabFiles folder. You will see errors, and then the tables will create and populate. There are six tables created and populated with this file. (3) Look at the content of the tables

2 Topics for today – 03/13/2014 Review and reinforce knowledge of joins. Discuss another twist on the join – a self-join. Practice multiple-table joins. Review non-correlated sub-queries. Learn about correlated sub-queries. Work on HW#7.

3

Know your tables How many relationships in the database? Which table is the child and which is the parent in each relationship? What are the data types of the primary keys? How many rows are in each table? Are there any concatenated keys in the database? 4

5 This is the result table I want to produce. Which underlying tables do I need to use?

Review joins Purpose is to combine more than one underlying table into a single result table. A join operation multiplies the two underlying tables: the rows are multiplied and the columns are added together to create a single result table. Cross join demonstration: SELECT * FROMxemp, xjobtitle

Types of joins: INNER JOIN Inner join: Combines the rows from two tables where the foreign key in the child table equals the primary key in the parent table. Result table: Consists only of those rows from both tables where the primary key = foreign key. Example: SELECT * FROMxemp emp INNER JOINxjobtitle jt ONemp.jobtitleID = jt.jobtitleID

Types of joins: OUTER JOIN Outer join: Combines the rows from two tables where the foreign key in the child table equals the primary key in the parent table. In addition, an outer join will include those rows in one (left, right) or both (full) tables that do not match the other table. Result table: Consists of those rows from both tables where the primary key = foreign key plus those rows from one or both tables where the primary key does not have a direct match. Example: SELECT * FROMxemp emp LEFT OUTER JOINxjobtitle jt ONemp.jobtitleID = jt.jobtitleID

Limit the columns to get the desired result 9 SELECT emp.lastname, emp.firstname, emp.hiredate, emp.billingrate, emp.jobtitleid, ISNULL(jt.title, 'No Matching Title') title FROMxemp emp LEFT OUTER JOINxjobtitle jt ONemp.jobtitleID = jt.jobtitleID ORDER BYemp.lastname

What do the two other outer joins do?? 10 SELECT emp.lastname, emp.firstname, emp.hiredate, emp.billingrate, emp.jobtitleid, ISNULL(jt.title, 'No Matching Title') title FROMxemp emp RIGHT OUTER JOINxjobtitle jt ONemp.jobtitleID = jt.jobtitleID ORDER BYemp.lastname SELECT emp.lastname, emp.firstname, emp.hiredate, emp.billingrate, emp.jobtitleid, ISNULL(jt.title, 'No Matching Title') title FROMxemp emp FULL OUTER JOINxjobtitle jt ONemp.jobtitleID = jt.jobtitleID ORDER BYemp.lastname

Self-join What if you want to add the last name of the manager for each employee? 11

12 Become familiar with the xEmp table. selectempid, lastname, firstname, managerid fromxEmp; Realize that the ManagerID in the EMP table represents the EmpID of the person who is the manager for that employee. To get the name of the manager (look at previous slide for the desired output from the query) requires that you search the EMP table twice: 1)Reading sequentially for each employee in the database; 2)Reading again to find the name of the manager for each employee. SQL does not let you read a table twice in a single query, so you must have two copies of the EMP table in memory in order to accomplish this operation. Those two copies must have table name aliases so that SQL Server (our DBMS) can differentiate them. In order to identify the name of the manager for a given employee, we need to join the two tables. There must be a foreign key to self-join two tables. In this sample, the foreign key is the ManagerID. Type in the code on the next slide to join two copies of the EMP table on the foreign key of ManagerID and primary key of EmpID.

SQL Self-Join 13 Type in this code to join two copies of the same table: SELECT emp.lastname, emp.firstname, emp.hiredate, emp.billingrate, emp.jobtitleid, ISNULL(jt.title, 'No Matching Title') title, ISNULL(manager.lastname, '**No Manager**') 'Manager Last Name' FROMxemp emp LEFT OUTER JOINxjobtitle jt ONemp.jobtitleID = jt.jobtitleID INNER JOIN xemp manager ON emp.managerid = manager.empid ORDER BY emp.lastname DOES IT WORK???

Let’s join some more tables! 14 SELECT emp.lastname, emp.firstname, emp.hiredate, emp.billingrate, emp.jobtitleid, ISNULL(jt.title, 'No Matching Title') title, ISNULL(manager.lastname, '**No Manager**') 'Manager Last Name', tw.StartWork, tw.Minutes FROMxemp emp LEFT OUTER JOINxjobtitle jt ONemp.jobtitleID = jt.jobtitleID LEFT OUTER JOIN xemp manager ON emp.managerid = manager.empid INNER JOIN xtimeworked tw ONtw.empid = emp.empid WHERE emp.lastname IN ('Chu', 'Jenkins') ORDER BY emp.lastname

15 SELECT emp.lastname, emp.firstname, emp.billingrate, ISNULL(jt.title, 'No Matching Title') title, ISNULL(manager.lastname, '**No Manager**') 'Manager Last Name', tw.StartWork, tw.Minutes, work.stdbillrate, work.description FROMxemp emp LEFT OUTER JOINxjobtitle jt ONemp.jobtitleID = jt.jobtitleID LEFT OUTER JOIN xemp manager ON emp.managerid = manager.empid INNER JOIN xtimeworked tw ONtw.empid = emp.empid INNER JOIN xwork work ON tw.worktypeid = work.worktypeid WHERE emp.lastname IN ('Chu', 'Jenkins') ORDER BYemp.lastname

16 SELECT emp.lastname, emp.firstname, emp.billingrate, ISNULL(jt.title, 'No Matching Title') title, ISNULL(manager.lastname, '**No Manager**') 'Manager Last Name', tw.StartWork, tw.Minutes, work.stdbillrate, work.description, contract.datesigned, contract.datedue FROMxemp emp LEFT OUTER JOINxjobtitle jt ONemp.jobtitleID = jt.jobtitleID LEFT OUTER JOIN xemp manager ON emp.managerid = manager.empid INNER JOIN xtimeworked tw ONtw.empid = emp.empid INNER JOIN xwork work ON tw.worktypeid = work.worktypeid INNER JOINxcontract contract ONtw.contractid = contract.contractid WHERE emp.lastname IN ('Chu', 'Jenkins') ORDER BYemp.lastname DOES IT WORK???

17 SELECT emp.lastname, emp.firstname, emp.billingrate, ISNULL(jt.title, 'No Matching Title') title, ISNULL(manager.lastname, '**No Manager**') 'Manager Last Name', tw.StartWork, tw.Minutes, work.stdbillrate, work.description, contract.datesigned, contract.datedue, client.name 'Client Name' FROMxemp emp LEFT OUTER JOINxjobtitle jt ONemp.jobtitleID = jt.jobtitleID LEFT OUTER JOIN xemp manager ON emp.managerid = manager.empid INNER JOIN xtimeworked tw ONtw.empid = emp.empid INNER JOIN xwork work ON tw.worktypeid = work.worktypeid LEFT OUTER JOINxcontract contract ONtw.contractid = contract.contractid LEFT OUTER JOIN xclient client ONcontract.clientid = client.clientid WHERE emp.lastname IN ('Chu', 'Jenkins') ORDER BYemp.lastname

Summarize time worked by contract 18

19 SELECT emp.lastname, emp.firstname, emp.billingrate, ISNULL(jt.title, 'No Matching Title') title, ISNULL(manager.lastname, '**No Manager**') 'Manager Last Name', contract.datesigned, contract.datedue, client.name 'Client Name', SUM(tw.Minutes) 'Total Minutes Worked' FROMxemp emp LEFT OUTER JOINxjobtitle jt ONemp.jobtitleID = jt.jobtitleID LEFT OUTER JOIN xemp manager ON emp.managerid = manager.empid INNER JOIN xtimeworked tw ONtw.empid = emp.empid LEFT OUTER JOINxcontract contract ONtw.contractid = contract.contractid LEFT OUTER JOIN xclient client ONcontract.clientid = client.clientid WHERE emp.lastname IN ('Chu', 'Jenkins') GROUP BY emp.lastname, emp.firstname, emp.billingrate, jt.title, manager.lastname, contract.datesigned, contract.datedue, client.name ORDER BYemp.lastname

20 What is a sub-query? A sub-query is a query embedded inside another query. The sub-query is executed in the normal operation of the query in which it is embedded. The sub-query will return an “answer” result table to the query in which it is embedded.

21 SELECT* FROMxEMP WHERE empid NOT IN (SELECT empid FROM xtimeworked) Find the employees who are not in the TIMEWORKED table via a subquery. Outer Query Inner Query

22 SELECT* FROMxEMP WHERE billingrate = (SELECT max(billingrate) FROM xemp) Find the employee who has the highest billing rate via a subquery. Outer Query Inner Query

23 Find which employees have a billing rate higher than the average billing rate using a subquery. SELECTempID, lastname, billingrate FROMxemp WHEREbillingrate > (SELECT AVG(billingrate) FROMxemp) The preceding sub-queries are called “non-correlated” sub-queries.

24 Example of a correlated sub-query Which employees have a higher BillingRate than the average BillingRate for their job title? SELECTjobtitleID, AVG(billingrate) AverageBillRate FROMxemp GROUP BY jobtitleID; Let’s start by understanding the query requirements:

Now put together a query using a correlated sub-query: SELECTempID, lastname, billingrate, jobtitleID FROMxemp empOuter WHEREbillingrate > (SELECT AVG(billingrate) FROM xemp empInner WHERE empOuter.jobtitleID = empInner.jobtitleID) Query passes the jobtitleID from the outer query to the inner query 25 Must alias the tables since two tables of the same name will be in main memory concurrently.

To get the job title from the job title table requires the use of a join SELECT empID, lastname, billingrate, empOuter.jobtitleID, title FROMxemp empOuter LEFT JOIN xjobtitle ON empOuter.jobtitleID = xjobtitle.jobtitleID WHERE billingrate > (SELECT AVG(billingrate) FROM xemp empInner WHERE empOuter.jobtitleID = empInner.jobtitleID) 26

27 Where are sub-queries placed in SQL code? Sub-queries can be embedded in the SELECT list, FROM, WHERE or HAVING clauses.  So far, all I’ve shown are sub-queries in the WHERE clause… Sub-queries can be used in INSERT, UPDATE or DELETE statements.

Example of a sub-query in the SELECT list: SELECTempID, lastname, empOuter.jobtitleID, title, billingrate "Employee Billing Rate", (SELECTAVG(billingrate) FROMxemp empSelect WHEREempOuter.jobtitleID = empSelect.jobtitleID) "Average Billing Rate" FROMxemp empOuter LEFT OUTER JOINxjobtitle ONempOuter.jobtitleID = xjobtitle.jobtitleID WHEREbillingrate > (SELECT AVG(billingrate) FROMxemp empInner WHEREempOuter.jobtitleID = empInner.jobtitleID) 28 How many copies of the EMP table are in memory when this query runs?