Displaying Data from Multiple Tables (Join). EMPNO DEPTNO LOC ----- ------- -------- 7839 10 NEW YORK 7698 30 CHICAGO 7782 10 NEW YORK 7566 20 DALLAS.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Displaying Data from Multiple Tables. Objectives After completing this lesson, you should Be able to do the following: Write SELECT statements to accessWrite.
4-1 Copyright  Oracle Corporation, All rights reserved. Types of Joins Equijoin Non-equijoin Outer join Self join.
Copyright  Oracle Corporation, All rights reserved. 3 Displaying Data from Multiple Tables.
Displaying Data from Multiple Tables. Objectives After completing this lesson, you should be able to do the following:  Write SELECT statements to access.
Displaying Data from Multiple Tables. Objectives After completing this lesson, you should be able to do the following: Write SELECT statements to access.
Chapter 4 JOINING TABLES & FUNCTION Lecture by Ty Rasmey
12-1 Copyright  Oracle Corporation, All rights reserved. What Is a View? EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
Subqueries 11. Objectives After completing this lesson, you should be able to do the following: Describe the types of problems that subqueries can solve.
1Eyad Alshareef Enhanced Guide to Oracle 10g Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data.
Copyright  Oracle Corporation, All rights reserved. 6 Subqueries.
6 6 Subqueries Important Legal Notice:  Materials on this lecture are from a book titled “Oracle Education” by Kochhar, Gravina, and Nathan (1999), published.
Copyright  Oracle Corporation, All rights reserved. 6 Writing Correlated Subqueries.
Session 3: SQL (B): Parts 3 & 4 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram.
4 Copyright © Oracle Corporation, All rights reserved. Displaying Data from Multiple Tables.
o At the end of this lesson, you will be able to:  Describe the life-cycle development phases  Discuss the theoretical and physical aspects of a relational.
4 Copyright © Oracle Corporation, All rights reserved. Displaying Data from Multiple Tables.
4-1 Copyright  Oracle Corporation, All rights reserved. Data Manipulation Language (DML)
4-1 Copyright  Oracle Corporation, All rights reserved. Displaying Data from Multiple Tables.
4 Copyright © Oracle Corporation, All rights reserved. Displaying Data from Multiple Tables.
Copyright © 2004, Oracle. All rights reserved. Lecture 6 Displaying Data from Multiple Tables ORACLE.
Displaying Data from Multiple Tables (Join) Displaying Data from Multiple Tables (Join) Displaying Data from Multiple Tables (Join Displaying Data from.
Lecture 8 Database Theory & Practice (2) : The Relational Data Model UFCEKG-20-2 Data, Schemas & Applications.
MSc IT UFIE8K-15-M Data Management Prakash Chatterjee Room 3P16
Subqueries.
Subqueries.
1 Information Retrieval and Use (IRU) CE An Introduction To SQL Part 1.
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.
SELECT Statements Lecture Notes Sree Nilakanta Fall 2010 (rev)
An Introduction To SQL - Part 1 (Special thanks to Geoff Leese)
Copyright س Oracle Corporation, All rights reserved. I Introduction.
Copyright  Oracle Corporation, All rights reserved. 2 Restricting and Sorting Data.
7 Multiple-Column Subqueries. 7-2 Objectives At the end of this lesson, you should be able to: Write a multiple-column subquery Describe and explain the.
SQL- DQL (Oracle Version). 2 SELECT Statement Syntax SELECT [DISTINCT] column_list FROM table_list [WHERE conditional expression] [GROUP BY column_list]
Join, Subqueries and set operators. Obtaining Data from Multiple Tables EMPLOYEES DEPARTMENTS … …
Session 2: SQL (A): Parts 1 and 2 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram.
4 Displaying Data from Multiple Tables Important Legal Notice:  Materials on this lecture are from a book titled “Oracle Education” by Kochhar, Gravina,
Copyright س Oracle Corporation, All rights reserved. 4 Displaying Data from Multiple Tables.
I-1 Copyright س Oracle Corporation, All rights reserved. Data Retrieval.
SQL: Part 2 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram. Not for commercial.
Multiple Table Queries (Inner Joins, Equijoins) Week 3.
4 Copyright © Oracle Corporation, All rights reserved. Displaying Data from Multiple Tables.
Copyright  Oracle Corporation, All rights reserved. 12 Creating Views.
Copyright س Oracle Corporation, All rights reserved. I Introduction.
6 Subqueries. 6-2 Objectives At the end of this lesson, you should be able to: Describe the types of problems that subqueries can solve Define subqueries.
Single-Row Functions. SQL Functions FunctionInput arg 1 arg 2 arg n Function performs action OutputResultvalue.
Copyright س Oracle Corporation, All rights reserved. 12 Creating Views.
Copyright  Oracle Corporation, All rights reserved. 4 Displaying Data from Multiple Tables.
Displaying Data from Multiple Tables (Join) Displaying Data from Multiple Tables (Join) Displaying Data from Multiple Tables (Join Displaying Data from.
4 Copyright © 2004, Oracle. All rights reserved. Displaying Data from Multiple Tables.
Copyright  Oracle Corporation, All rights reserved. 4 Displaying Data from Multiple Tables.
Displaying Data from Multiple Tables. Objectives After completing this lesson, you should be able to do the following: –Write SELECT statements to access.
4 Displaying Data from Multiple Tables. 4-2 Objectives At the end of this lesson, you should be able to: Write SELECT statements to access data from more.
4 Copyright © Oracle Corporation, All rights reserved. Displaying Data from Multiple Tables.
Communicating with a RDBMS Using SQL Database SQL> SELECT loc 2 FROM dept; SQL> SELECT loc 2 FROM dept; SQL statement is entered Statement is sent to database.
Displaying Data from Multiple Tables
Displaying Data from Multiple Tables
Subqueries.
Subqueries Schedule: Timing Topic 25 minutes Lecture
CH3 Part2 Displaying Data from Multiple Tables (Join) Sub queries
What Is a View? EMPNO ENAME JOB EMP Table EMPVU10 View
(SQL) Displaying Data from Multiple Tables
Lecture 16 : The Relational Data Model
Subqueries Schedule: Timing Topic 25 minutes Lecture
Lecture 16 : The Relational Data Model
Displaying Data from Multiple Tables
Displaying Data from Multiple Tables
Subqueries Schedule: Timing Topic 25 minutes Lecture
Presentation transcript:

Displaying Data from Multiple Tables (Join)

EMPNO DEPTNO LOC NEW YORK CHICAGO NEW YORK DALLAS CHICAGO CHICAGO rows selected. EMPNO DEPTNO LOC NEW YORK CHICAGO NEW YORK DALLAS CHICAGO CHICAGO rows selected. Obtaining Data from Multiple Tables EMPDEPT EMPNOENAME...DEPTNO KING BLAKE MILLER DEPTNO DNAME LOC ACCOUNTINGNEW YORK 20RESEARCHDALLAS 30SALESCHICAGO 40OPERATIONSBOSTON

What Is a Join? Use a join to query data from more than one table. Use a join to query data from more than one table. Write the join condition in the WHERE clause. Write the join condition in the WHERE clause. Prefix the column name with the table name when the same column name appears in more than one table. Prefix the column name with the table name when the same column name appears in more than one table. Use a join to query data from more than one table. Use a join to query data from more than one table. Write the join condition in the WHERE clause. Write the join condition in the WHERE clause. Prefix the column name with the table name when the same column name appears in more than one table. Prefix the column name with the table name when the same column name appears in more than one table. SELECTtable1.column, table2.column FROMtable1, table2 WHEREtable1.column1 = table2.column2; SELECTtable1.column, table2.column FROMtable1, table2 WHEREtable1.column1 = table2.column2;

Cartesian Product A Cartesian product is formed when: A Cartesian product is formed when: A join condition is omitted A join condition is omitted A join condition is invalid A join condition is invalid All rows in the first table are joined to all rows in the second table All rows in the first table are joined to all rows in the second table To avoid a Cartesian product, always include a valid join condition in a WHERE clause. To avoid a Cartesian product, always include a valid join condition in a WHERE clause. A Cartesian product is formed when: A Cartesian product is formed when: A join condition is omitted A join condition is omitted A join condition is invalid A join condition is invalid All rows in the first table are joined to all rows in the second table All rows in the first table are joined to all rows in the second table To avoid a Cartesian product, always include a valid join condition in a WHERE clause. To avoid a Cartesian product, always include a valid join condition in a WHERE clause.

Generating a Cartesian Product ENAME DNAME KINGACCOUNTING BLAKE ACCOUNTING... KINGRESEARCH BLAKE RESEARCH rows selected. ENAME DNAME KINGACCOUNTING BLAKE ACCOUNTING... KINGRESEARCH BLAKE RESEARCH rows selected. EMP (14 rows) DEPT (4 rows) EMPNOENAME...DEPTNO KING BLAKE MILLER EMPNOENAME...DEPTNO KING BLAKE MILLER DEPTNO DNAME LOC ACCOUNTINGNEW YORK 20RESEARCHDALLAS 30SALESCHICAGO 40OPERATIONSBOSTON DEPTNO DNAME LOC ACCOUNTINGNEW YORK 20RESEARCHDALLAS 30SALESCHICAGO 40OPERATIONSBOSTON “Cartesian product: 14*4=56 rows”

Types of Joins Equijoin Non-equijoin Outer join Self join

What Is an Equijoin? EMP DEPT EMPNO ENAME DEPTNO KING BLAKE CLARK JONES MARTIN ALLEN TURNER JAMES WARD FORD SMITH rows selected. DEPTNO DNAME LOC ACCOUNTING NEW YORK 30 SALES CHICAGO 10 ACCOUNTINGNEW YORK 20 RESEARCHDALLAS 30 SALES CHICAGO 20 RESEARCHDALLAS rows selected. Foreign key Primary key

Retrieving Records with Equijoins SQL> SELECT emp.empno, emp.ename, emp.deptno, 2dept.deptno, dept.loc 3 FROM emp, dept 4 WHERE emp.deptno=dept.deptno; EMPNO ENAME DEPTNO DEPTNO LOC KING NEW YORK 7698 BLAKE CHICAGO 7782 CLARK NEW YORK 7566 JONES DALLAS rows selected.

Qualifying Ambiguous Column Names Use table prefixes to qualify column names that are in multiple tables. Use table prefixes to qualify column names that are in multiple tables. Improve performance by using table prefixes. Improve performance by using table prefixes. Distinguish columns that have identical names but reside in different tables by using column aliases. Distinguish columns that have identical names but reside in different tables by using column aliases. Use table prefixes to qualify column names that are in multiple tables. Use table prefixes to qualify column names that are in multiple tables. Improve performance by using table prefixes. Improve performance by using table prefixes. Distinguish columns that have identical names but reside in different tables by using column aliases. Distinguish columns that have identical names but reside in different tables by using column aliases.

Additional Search Conditions Using the AND Operator EMPDEPT EMPNO ENAME DEPTNO KING BLAKE CLARK JONES MARTIN ALLEN TURNER JAMES WARD FORD SMITH rows selected. DEPTNO DNAME LOC ACCOUNTINGNEW YORK 30SALES CHICAGO 10 ACCOUNTINGNEW YORK 20 RESEARCHDALLAS 30 SALES CHICAGO 20 RESEARCHDALLAS rows selected.

Using Table Aliases Simplify queries by using table aliases. Simplify queries by using table aliases. SQL> SELECT emp.empno, emp.ename, emp.deptno, 2 dept.deptno, dept.loc 3 FROM emp, dept 4 WHERE emp.deptno=dept.deptno; SQL> SELECT e.empno, e.ename, e.deptno, 2 d.deptno, d.loc 3 FROM emp e, dept d 4 WHERE e.deptno= d.deptno;

Joining More Than Two Tables NAMECUSTID JOCKSPORTS 100 TKB SPORT SHOP 101 VOLLYRITE 102 JUST TENNIS 103 K+T SPORTS 105 SHAPE UP 106 WOMENS SPORTS rows selected. NAMECUSTID JOCKSPORTS 100 TKB SPORT SHOP 101 VOLLYRITE 102 JUST TENNIS 103 K+T SPORTS 105 SHAPE UP 106 WOMENS SPORTS rows selected. CUSTOMER CUSTID ORDID rows selected. CUSTID ORDID rows selected.ORD ORDID ITEMID rows selected. ORDID ITEMID rows selected.ITEM

Non-EquijoinsNon-Equijoins EMPSALGRADE “salary in the EMP table is between low salary and high salary in the SALGRADE table” EMPNO ENAME SAL KING BLAKE CLARK JONES MARTIN ALLEN TURNER JAMES rows selected. GRADE LOSAL HISAL

Retrieving Records with Non-Equijoins ENAME SAL GRADE JAMES SMITH ADAMS rows selected. SQL> SELECT e.ename, e.sal, s.grade 2FROMemp e, salgrade s 3WHERE e.sal 4BETWEEN s.losal AND s.hisal;

Outer Joins EMP DEPT No employee in the OPERATIONS department ENAMEDEPTNO KING10 BLAKE30 CLARK10 JONES20... DEPTNO DNAME ACCOUNTING 30 SALES 10 ACCOUNTING 20RESEARCH... 40OPERATIONS

Outer Joins You use an outer join to also see rows that do not usually meet the join condition. You use an outer join to also see rows that do not usually meet the join condition. Outer join operator is the plus sign (+). Outer join operator is the plus sign (+). You use an outer join to also see rows that do not usually meet the join condition. You use an outer join to also see rows that do not usually meet the join condition. Outer join operator is the plus sign (+). Outer join operator is the plus sign (+). SELECTtable1.column, table2.column FROMtable1, table2 WHEREtable1.column(+) = table2.column; SELECTtable1.column, table2.column FROMtable1, table2 WHEREtable1.column(+) = table2.column; SELECTtable1.column, table2.column FROMtable1, table2 WHEREtable1.column = table2.column(+); SELECTtable1.column, table2.column FROMtable1, table2 WHEREtable1.column = table2.column(+);

Using Outer Joins SQL> SELECTe.ename, d.deptno, d.dname 2 FROMemp e, dept d 3 WHEREe.deptno(+) = d.deptno 4 ORDER BYe.deptno; ENAME DEPTNO DNAME KING 10 ACCOUNTING CLARK 10 ACCOUNTING OPERATIONS 15 rows selected.

Outer Joins Student 105 (Michael Connoly) does not have any ENROLLMENT records

Outer Joins No records retrieved for Michael: No records retrieved for Michael:

Outer Joins To include records in first (inner) table, even when they do not have matching records in second (outer) table, place outer join marker (+) beside outer table name in join clause

Outer Joins Outer join marker

Self Joins EMP (WORKER) EMP (MANAGER) “MGR in the WORKER table is equal to EMPNO in the MANAGER table” EMPNOENAME MGR KING 7698BLAKE CLARK JONES MARTIN ALLEN7698 EMPNOENAME KING 7698BLAKE

Joining a Table to Itself WORKER.ENAME||'WORKSFOR'||MANAG BLAKE works for KING CLARK works for KING JONES works for KING MARTIN works for BLAKE rows selected. WORKER.ENAME||'WORKSFOR'||MANAG BLAKE works for KING CLARK works for KING JONES works for KING MARTIN works for BLAKE rows selected. SQL> SELECT worker.ename||' works for '||manager.ename 2 FROM emp worker, emp manager 3 WHERE worker.mgr = manager.empno;

SummarySummary Equijoin Non-equijoin Outer join Self join SELECTtable1.column, table2.column FROMtable1, table2 WHEREtable1.column1 = table2.column2; SELECTtable1.column, table2.column FROMtable1, table2 WHEREtable1.column1 = table2.column2;

Sub queries

SubqueriesSubqueries The subquery (inner query) executes once before the main query. The subquery (inner query) executes once before the main query. The result of the subquery is used by the main query (outer query). The result of the subquery is used by the main query (outer query). The subquery (inner query) executes once before the main query. The subquery (inner query) executes once before the main query. The result of the subquery is used by the main query (outer query). The result of the subquery is used by the main query (outer query). SELECTselect_list FROMtable WHEREexpr operator (SELECTselect_list FROMtable);

2975 SQL> SELECT ename 2 FROM emp 3 WHERE sal > 4 (SELECT sal 5 FROM emp 6 WHERE empno=7566); Using a Subquery ENAME KING FORD SCOTT ENAME KING FORD SCOTT

Guidelines for Using Subqueries Enclose subqueries in parentheses. Enclose subqueries in parentheses. Place subqueries on the right side of the comparison operator. Place subqueries on the right side of the comparison operator. Do not add an ORDER BY clause to a subquery. Do not add an ORDER BY clause to a subquery. Use single-row operators with single-row subqueries. Use single-row operators with single-row subqueries. Use multiple-row operators with multiple-row subqueries. Use multiple-row operators with multiple-row subqueries. Enclose subqueries in parentheses. Enclose subqueries in parentheses. Place subqueries on the right side of the comparison operator. Place subqueries on the right side of the comparison operator. Do not add an ORDER BY clause to a subquery. Do not add an ORDER BY clause to a subquery. Use single-row operators with single-row subqueries. Use single-row operators with single-row subqueries. Use multiple-row operators with multiple-row subqueries. Use multiple-row operators with multiple-row subqueries.

Types of Subqueries Single-row subquery Single-row subquery Main query Subquery returns CLERK Multiple-row subquery CLERKMANAGER Main query Subquery returns Multiple-column subquery CLERK 7900 MANAGER 7698 Main query Subquery returns

Executing Single-Row Subqueries CLERK 1100 ENAME JOB MILLER CLERK ENAME JOB MILLER CLERK SQL> SELECT ename, job 2 FROM emp 3 WHERE job = 4(SELECT job 5 FROM emp 6 WHERE empno = 7369) 7 AND sal > 8(SELECT sal 9FROMemp 10WHEREempno = 7876);

Using Group Functions in a Subquery 800 ENAME JOB SAL SMITH CLERK 800 ENAME JOB SAL SMITH CLERK 800 SQL> SELECTename, job, sal 2 FROMemp 3 WHEREsal = 4(SELECTMIN(sal) 5FROMemp);

HAVING Clause with Subqueries The Oracle Server executes subqueries first. The Oracle Server executes subqueries first. The Oracle Server returns results into the HAVING clause of the main query. The Oracle Server returns results into the HAVING clause of the main query. The Oracle Server executes subqueries first. The Oracle Server executes subqueries first. The Oracle Server returns results into the HAVING clause of the main query. The Oracle Server returns results into the HAVING clause of the main query. 800 SQL> SELECTdeptno, MIN(sal) 2 FROMemp 3 GROUP BYdeptno 4 HAVINGMIN(sal) > 5(SELECTMIN(sal) 6FROMemp 7WHEREdeptno = 20);

What Is Wrong with This Statement? ERROR: ORA-01427: single-row subquery returns more than one row no rows selected ERROR: ORA-01427: single-row subquery returns more than one row no rows selected SQL> SELECT empno, ename 2 FROM emp 3 WHERE sal = 4(SELECT MIN(sal) 5FROM emp 6GROUP BY deptno); Single-row operator with multiple-row subquery

Will This Statement Work? no rows selected Subquery returns no values SQL> SELECT ename, job 2 FROM emp 3 WHERE job = 4(SELECTjob 5FROMemp 6WHEREename='SMYTHE');

Multiple-Row Subqueries Return more than one row Return more than one row Use multiple-row comparison operators Use multiple-row comparison operators Return more than one row Return more than one row Use multiple-row comparison operators Use multiple-row comparison operators Operator IN ANY ALL Meaning Equal to any member in the list Compare value to each value returned by the subquery Compare value to every value returned by the subquery

Creating Views

Logical table based on a query Logical table based on a query Does not physically exist in the database Does not physically exist in the database Presents data in a different format from underlying tables Presents data in a different format from underlying tables Uses: Uses: Security Security Simplifying complex queries Simplifying complex queries Database Views

Simple Views and Complex Views FeatureSimple ViewsComplex Views Number of tablesOneOne or more Contain functionsNoYes Contain groups of dataNoYes DML through viewYesNot always

Creating a View You embed a subquery within the CREATE VIEW statement. You embed a subquery within the CREATE VIEW statement. The subquery can contain complex SELECT syntax. The subquery can contain complex SELECT syntax. The subquery cannot contain an ORDER BY clause. The subquery cannot contain an ORDER BY clause. You embed a subquery within the CREATE VIEW statement. You embed a subquery within the CREATE VIEW statement. The subquery can contain complex SELECT syntax. The subquery can contain complex SELECT syntax. The subquery cannot contain an ORDER BY clause. The subquery cannot contain an ORDER BY clause. CREATE [OR REPLACE] VIEW view_name AS subquery; CREATE [OR REPLACE] VIEW view_name AS subquery;

Creating a View Create a view, EMPVU10, that contains details of employees in department 10. Create a view, EMPVU10, that contains details of employees in department 10. Describe the structure of the view by using the SQL*Plus DESCRIBE command. SQL> DESCRIBE empvu10 SQL> CREATE VIEW empvu10 2 AS SELECTempno, ename, job 3 FROMemp 4 WHEREdeptno = 10; View created.

Retrieving Data from a View EMPLOYEE_NUMBER NAME SALARY BLAKE MARTIN ALLEN TURNER JAMES WARD rows selected. EMPLOYEE_NUMBER NAME SALARY BLAKE MARTIN ALLEN TURNER JAMES WARD rows selected. SQL> SELECT * 2 FROMsalvu30;

Removing a View Remove a view without losing data because a view is based on underlying tables in the database. Remove a view without losing data because a view is based on underlying tables in the database. SQL> DROP VIEW empvu10; View dropped. DROP VIEW view;

Performs set operations on outputs of two unrelated queries Performs set operations on outputs of two unrelated queries Both queries must have: Both queries must have: same number of display fields same number of display fields corresponding display fields must have same data type corresponding display fields must have same data type Using Set Operators in Queries

UNION: combines results, suppresses duplicate rows UNION: combines results, suppresses duplicate rows UNION ALL: combines results, displays duplicates UNION ALL: combines results, displays duplicates INTERSECT: finds matching rows INTERSECT: finds matching rows MINUS: returns the difference between returned record sets MINUS: returns the difference between returned record sets Query Set Operators

Synonyms Alternate name for a table Alternate name for a table Allows you to not have to preface table with owner’s username when you are querying a table that belongs to another user Allows you to not have to preface table with owner’s username when you are querying a table that belongs to another user

Public Synonyms Can only be created by a DBA Can only be created by a DBA Syntax: Syntax: CREATE PUBLIC SYNONYM synonym_name FOR owner_name.tablename; All users with privileges to use table can then use synonym instead of owner_name.tablename All users with privileges to use table can then use synonym instead of owner_name.tablename

Private Synonyms You can create private synonyms for any tables that you have privileges to use You can create private synonyms for any tables that you have privileges to use Only you can use the synonym Only you can use the synonym Syntax: Syntax: CREATE SYNONYM synonym_name FOR table_name.table_name;