displaying data from multiple tables (join). empno deptno loc ----- ------- -------- 7839 10 new...

47
Displaying Data from Multiple Tables (Join)

Upload: henry-norman

Post on 01-Jan-2016

225 views

Category:

Documents


2 download

TRANSCRIPT

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

Displaying Data from Multiple Tables

(Join)

Displaying Data from Multiple Tables

(Join)

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

EMPNO DEPTNO LOC----- ------- -------- 7839 10 NEW YORK 7698 30 CHICAGO 7782 10 NEW YORK 7566 20 DALLAS 7654 30 CHICAGO 7499 30 CHICAGO...14 rows selected.

EMPNO DEPTNO LOC----- ------- -------- 7839 10 NEW YORK 7698 30 CHICAGO 7782 10 NEW YORK 7566 20 DALLAS 7654 30 CHICAGO 7499 30 CHICAGO...14 rows selected.

Obtaining Data from Obtaining Data from Multiple TablesMultiple Tables

Obtaining Data from Obtaining Data from Multiple TablesMultiple Tables

EMP EMP DEPT DEPT EMPNO ENAME ... DEPTNO------ ----- ... ------ 7839 KING ... 10 7698 BLAKE ... 30 ... 7934 MILLER ... 10

DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON

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

What Is a Join?What Is a Join?What Is a Join?What Is a Join?

Use a join to query data from Use a join to query data from more than one table.more than one table.

Write the join condition in the Write the join condition in the WHERE clause.WHERE clause.

Prefix the column name with the Prefix the column name with the table name when the same column table name when the same column name appears in more than one name appears in more than one table.table.

Use a join to query data from Use a join to query data from more than one table.more than one table.

Write the join condition in the Write the join condition in the WHERE clause.WHERE clause.

Prefix the column name with the Prefix the column name with the table name when the same column table name when the same column name appears in more than one name appears in more than one table.table.

SELECT table1.column, table2.columnFROM table1, table2WHERE table1.column1 = table2.column2;

SELECT table1.column, table2.columnFROM table1, table2WHERE table1.column1 = table2.column2;

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

Cartesian ProductCartesian ProductCartesian ProductCartesian Product

A Cartesian product is formed A Cartesian product is formed when:when: A join condition is omittedA join condition is omitted A join condition is invalidA join condition is invalid All rows in the first table are joined to All rows in the first table are joined to

all rows in the second tableall rows in the second table To avoid a Cartesian product, To avoid a Cartesian product,

always include a valid join always include a valid join condition in a WHERE clause.condition in a WHERE clause.

A Cartesian product is formed A Cartesian product is formed when:when: A join condition is omittedA join condition is omitted A join condition is invalidA join condition is invalid All rows in the first table are joined to All rows in the first table are joined to

all rows in the second tableall rows in the second table To avoid a Cartesian product, To avoid a Cartesian product,

always include a valid join always include a valid join condition in a WHERE clause.condition in a WHERE clause.

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

Generating a Cartesian Generating a Cartesian ProductProduct

Generating a Cartesian Generating a Cartesian ProductProduct

ENAME DNAME------ ----------KING ACCOUNTINGBLAKE ACCOUNTING ...KING RESEARCHBLAKE RESEARCH...56 rows selected.

ENAME DNAME------ ----------KING ACCOUNTINGBLAKE ACCOUNTING ...KING RESEARCHBLAKE RESEARCH...56 rows selected.

EMP (14 rows) EMP (14 rows) DEPT (4 rows) DEPT (4 rows)

EMPNO ENAME ... DEPTNO------ ----- ... ------ 7839 KING ... 10 7698 BLAKE ... 30 ... 7934 MILLER ... 10

EMPNO ENAME ... DEPTNO------ ----- ... ------ 7839 KING ... 10 7698 BLAKE ... 30 ... 7934 MILLER ... 10

DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON

DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON

““CartesianCartesianproduct: product:

14*4=56 rows”14*4=56 rows”

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

Types of JoinsTypes of JoinsTypes of JoinsTypes of Joins

EquijoinEquijoin Non-equijoinNon-equijoin Outer joinOuter join Self joinSelf join

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

What Is an Equijoin?What Is an Equijoin?What Is an Equijoin?What Is an Equijoin?EMP EMP DEPT DEPT EMPNO ENAME DEPTNO------ ------- ------- 7839 KING 10 7698 BLAKE 30 7782 CLARK 10 7566 JONES 20 7654 MARTIN 30 7499 ALLEN 30 7844 TURNER 30 7900 JAMES 30 7521 WARD 30 7902 FORD 20 7369 SMITH 20...14 rows selected.

DEPTNO DNAME LOC ------- ---------- -------- 10 ACCOUNTING NEW YORK 30 SALES CHICAGO 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 30 SALES CHICAGO 30 SALES CHICAGO 30 SALES CHICAGO 30 SALES CHICAGO 20 RESEARCH DALLAS 20 RESEARCH DALLAS...14 rows selected.

Foreign keyForeign key Primary keyPrimary key

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

Retrieving Records Retrieving Records with Equijoinswith Equijoins

Retrieving Records Retrieving Records with Equijoinswith Equijoins

SQL> SELECT emp.empno, emp.ename, emp.deptno, 2 dept.deptno, dept.loc 3 FROM emp, dept 4 WHERE emp.deptno=dept.deptno;

EMPNO ENAME DEPTNO DEPTNO LOC----- ------ ------ ------ --------- 7839 KING 10 10 NEW YORK 7698 BLAKE 30 30 CHICAGO 7782 CLARK 10 10 NEW YORK 7566 JONES 20 20 DALLAS...14 rows selected.

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

Qualifying Ambiguous Qualifying Ambiguous Column NamesColumn Names

Qualifying Ambiguous Qualifying Ambiguous Column NamesColumn Names

Use table prefixes to qualify Use table prefixes to qualify column names that are in multiple column names that are in multiple tables.tables.

Improve performance by using Improve performance by using table prefixes.table prefixes.

Distinguish columns that have Distinguish columns that have identical names but reside in identical names but reside in different tables by using column different tables by using column aliases.aliases.

Use table prefixes to qualify Use table prefixes to qualify column names that are in multiple column names that are in multiple tables.tables.

Improve performance by using Improve performance by using table prefixes.table prefixes.

Distinguish columns that have Distinguish columns that have identical names but reside in identical names but reside in different tables by using column different tables by using column aliases.aliases.

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

Additional Search Additional Search ConditionsConditions

Using the AND Operator Using the AND Operator

Additional Search Additional Search ConditionsConditions

Using the AND Operator Using the AND Operator EMP EMP DEPT DEPT EMPNO ENAME DEPTNO------ ------- ------- 7839 KING 10 7698 BLAKE 30 7782 CLARK 10 7566 JONES 20 7654 MARTIN 30 7499 ALLEN 30 7844 TURNER 30 7900 JAMES 30 7521 WARD 30 7902 FORD 20 7369 SMITH 20...14 rows selected.

DEPTNO DNAME LOC ------ --------- -------- 10 ACCOUNTING NEW YORK 30 SALES CHICAGO 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 30 SALES CHICAGO 30 SALES CHICAGO 30 SALES CHICAGO 30 SALES CHICAGO 20 RESEARCH DALLAS 20 RESEARCH DALLAS...14 rows selected.

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

Using Table AliasesUsing Table AliasesUsing Table AliasesUsing Table Aliases Simplify queries by using table Simplify queries by using table

aliases.aliases.

Simplify queries by using table Simplify queries by using table aliases.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;

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

Joining More Than Two Joining More Than Two TablesTables

Joining More Than Two Joining More Than Two TablesTables

NAME CUSTID----------- ------JOCKSPORTS 100TKB SPORT SHOP 101VOLLYRITE 102JUST TENNIS 103K+T SPORTS 105SHAPE UP 106WOMENS SPORTS 107... ...9 rows selected.

NAME CUSTID----------- ------JOCKSPORTS 100TKB SPORT SHOP 101VOLLYRITE 102JUST TENNIS 103K+T SPORTS 105SHAPE UP 106WOMENS SPORTS 107... ...9 rows selected.

CUSTOMER CUSTOMER

CUSTID ORDID------- ------- 101 610 102 611 104 612 106 601 102 602 106 604 106 605... 21 rows selected.

CUSTID ORDID------- ------- 101 610 102 611 104 612 106 601 102 602 106 604 106 605... 21 rows selected.

ORD ORD

ORDID ITEMID------ ------- 610 3 611 1 612 1 601 1 602 1...64 rows selected.

ORDID ITEMID------ ------- 610 3 611 1 612 1 601 1 602 1...64 rows selected.

ITEM ITEM

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

Non-EquijoinsNon-EquijoinsNon-EquijoinsNon-EquijoinsEMPEMP SALGRADESALGRADE

““salary in the EMP salary in the EMP table is between table is between low salary and high low salary and high salary in the SALGRADEsalary in the SALGRADEtable”table”

EMPNO ENAME SAL------ ------- ------ 7839 KING 5000 7698 BLAKE 2850 7782 CLARK 2450 7566 JONES 2975 7654 MARTIN 1250 7499 ALLEN 1600 7844 TURNER 1500 7900 JAMES 950...14 rows selected.

GRADE LOSAL HISAL----- ----- ------1 700 12002 1201 14003 1401 20004 2001 30005 3001 9999

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

Retrieving Records Retrieving Records with Non-Equijoinswith Non-EquijoinsRetrieving Records Retrieving Records with Non-Equijoinswith Non-Equijoins

ENAME SAL GRADE---------- --------- ---------JAMES 950 1SMITH 800 1ADAMS 1100 1...14 rows selected.

SQL> SELECT e.ename, e.sal, s.grade

2 FROM emp e, salgrade s

3 WHERE e.sal

4 BETWEEN s.losal AND s.hisal;

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

Outer JoinsOuter JoinsOuter JoinsOuter JoinsEMP EMP DEPT DEPT

No employee in theNo employee in theOPERATIONS departmentOPERATIONS department

ENAME DEPTNO----- ------KING 10BLAKE 30CLARK 10JONES 20...

DEPTNO DNAME------ ----------10 ACCOUNTING30 SALES10 ACCOUNTING20 RESEARCH...40 OPERATIONS

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

Outer JoinsOuter JoinsOuter JoinsOuter Joins You use an outer join to also see You use an outer join to also see

rows that do not usually meet the rows that do not usually meet the join condition.join condition.

Outer join operator is the plus sign Outer join operator is the plus sign (+)(+)..

You use an outer join to also see You use an outer join to also see rows that do not usually meet the rows that do not usually meet the join condition.join condition.

Outer join operator is the plus sign Outer join operator is the plus sign (+)(+)..SELECT table1.column, table2.column

FROM table1, table2

WHERE table1.column(+) = table2.column;

SELECT table1.column, table2.column

FROM table1, table2

WHERE table1.column(+) = table2.column;

SELECT table1.column, table2.column

FROM table1, table2

WHERE table1.column = table2.column(+);

SELECT table1.column, table2.column

FROM table1, table2

WHERE table1.column = table2.column(+);

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

Using Outer JoinsUsing Outer JoinsUsing Outer JoinsUsing Outer Joins

SQL> SELECT e.ename, d.deptno, d.dname

2 FROM emp e, dept d

3 WHERE e.deptno(+) = d.deptno

4 ORDER BY e.deptno;

ENAME DEPTNO DNAME---------- --------- -------------KING 10 ACCOUNTINGCLARK 10 ACCOUNTING... 40 OPERATIONS15 rows selected.

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

Outer JoinsOuter Joins

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

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

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

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

Outer JoinsOuter 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

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

Outer JoinsOuter JoinsOuter join marker

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

Self JoinsSelf JoinsSelf JoinsSelf Joins

EMP (WORKER)EMP (WORKER) EMP (MANAGER)EMP (MANAGER)

““MGR in the WORKER table is equal to EMPNO in the MGR in the WORKER table is equal to EMPNO in the MANAGER table”MANAGER table”

EMPNO ENAME MGR----- ------ ---- 7839 KING 7698 BLAKE 7839 7782 CLARK 7839 7566 JONES 7839 7654 MARTIN 7698 7499 ALLEN 7698

EMPNO ENAME----- --------

7839 KING 7839 KING 7839 KING 7698 BLAKE 7698 BLAKE

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

Joining a Table to ItselfJoining a Table to ItselfJoining a Table to ItselfJoining a Table to Itself

WORKER.ENAME||'WORKSFOR'||MANAG-------------------------------BLAKE works for KINGCLARK works for KINGJONES works for KINGMARTIN works for BLAKE...13 rows selected.

WORKER.ENAME||'WORKSFOR'||MANAG-------------------------------BLAKE works for KINGCLARK works for KINGJONES works for KINGMARTIN works for BLAKE...13 rows selected.

SQL> SELECT worker.ename||' works for '||manager.ename

2 FROM emp worker, emp manager

3 WHERE worker.mgr = manager.empno;

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

SummarySummarySummarySummary

EquijoinEquijoin Non-equijoinNon-equijoin Outer joinOuter join Self joinSelf join

SELECT table1.column, table2.columnFROM table1, table2WHERE table1.column1 = table2.column2;

SELECT table1.column, table2.columnFROM table1, table2WHERE table1.column1 = table2.column2;

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

Sub queriesSub queries

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

SubqueriesSubqueriesSubqueriesSubqueries

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 The result of the subquery is used by the main query (outer

query).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 The result of the subquery is used by the main query (outer

query).query).

SELECT select_listFROM tableWHERE expr operator

(SELECT select_list FROM table);

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

2975

SQL> SELECT ename 2 FROM emp 3 WHERE sal > 4 (SELECT sal 5 FROM emp 6 WHERE empno=7566);

Using a SubqueryUsing a SubqueryUsing a SubqueryUsing a Subquery

ENAME----------KINGFORDSCOTT

ENAME----------KINGFORDSCOTT

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

Guidelines for Using Guidelines for Using SubqueriesSubqueries

Guidelines for Using Guidelines for Using SubqueriesSubqueries

Enclose subqueries in parentheses. Enclose subqueries in parentheses. Place subqueries on the right side Place subqueries on the right side

of the comparison operator.of the comparison operator. Do not add an ORDER BY clause to Do not add an ORDER BY clause to

a subquery.a subquery. Use single-row operators with Use single-row operators with

single-row subqueries.single-row subqueries. Use multiple-row operators with Use multiple-row operators with

multiple-row subqueries.multiple-row subqueries.

Enclose subqueries in parentheses. Enclose subqueries in parentheses. Place subqueries on the right side Place subqueries on the right side

of the comparison operator.of the comparison operator. Do not add an ORDER BY clause to Do not add an ORDER BY clause to

a subquery.a subquery. Use single-row operators with Use single-row operators with

single-row subqueries.single-row subqueries. Use multiple-row operators with Use multiple-row operators with

multiple-row subqueries.multiple-row subqueries.

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

Types of SubqueriesTypes of SubqueriesTypes of SubqueriesTypes of Subqueries Single-row subquerySingle-row subquery Single-row subquerySingle-row subquery

Main query

Subquery returnsreturns

CLERKCLERK

• Multiple-row subquery• Multiple-row subquery

CLERKCLERKMANAGERMANAGER

Main query

Subquery returnsreturns

• Multiple-column subquery• Multiple-column subquery

CLERK 7900CLERK 7900MANAGER 7698MANAGER 7698

Main query

Subquery returnsreturns

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

Executing Single-Row Executing Single-Row SubqueriesSubqueries

Executing Single-Row Executing Single-Row SubqueriesSubqueries

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 9 FROM emp 10 WHERE empno = 7876);

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

Using Group Functions Using Group Functions in a Subqueryin a Subquery

Using Group Functions Using Group Functions in a Subqueryin a Subquery

800

ENAME JOB SAL---------- --------- ---------SMITH CLERK 800

ENAME JOB SAL---------- --------- ---------SMITH CLERK 800

SQL> SELECT ename, job, sal 2 FROM emp 3 WHERE sal = 4 (SELECT MIN(sal) 5 FROM emp);

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

HAVING Clause with HAVING Clause with SubqueriesSubqueries

HAVING Clause with HAVING Clause with SubqueriesSubqueries

The Oracle Server executes The Oracle Server executes subqueries first.subqueries first.

The Oracle Server returns results The Oracle Server returns results into the HAVING clause of the into the HAVING clause of the main query.main query.

The Oracle Server executes The Oracle Server executes subqueries first.subqueries first.

The Oracle Server returns results The Oracle Server returns results into the HAVING clause of the into the HAVING clause of the main query.main query.

800

SQL> SELECT deptno, MIN(sal) 2 FROM emp 3 GROUP BY deptno 4 HAVING MIN(sal) > 5 (SELECT MIN(sal) 6 FROM emp 7 WHERE deptno = 20);

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

What Is Wrong What Is Wrong with This Statement?with This Statement?

What Is Wrong What Is Wrong with This Statement?with This Statement?

ERROR:ORA-01427: single-row subquery returns more thanone row

no rows selected

ERROR:ORA-01427: single-row subquery returns more thanone row

no rows selected

SQL> SELECT empno, ename 2 FROM emp 3 WHERE sal = 4 (SELECT MIN(sal) 5 FROM emp 6 GROUP BY deptno);

Single-row operator with

Single-row operator with

multiple-row subquery

multiple-row subquery

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

Will This Statement Will This Statement Work?Work?

Will This Statement Will This Statement Work?Work?

no rows selectedno rows selected

Subquery returns no values

Subquery returns no values

SQL> SELECT ename, job 2 FROM emp 3 WHERE job = 4 (SELECT job 5 FROM emp 6 WHERE ename='SMYTHE');

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

Multiple-Row SubqueriesMultiple-Row SubqueriesMultiple-Row SubqueriesMultiple-Row Subqueries Return more than one rowReturn more than one row Use multiple-row comparison Use multiple-row comparison

operatorsoperators

Return more than one rowReturn more than one row Use multiple-row comparison Use multiple-row comparison

operatorsoperatorsOperator

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

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

Creating ViewsCreating Views

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

Logical table based on a queryLogical table based on a query Does not physically exist in the Does not physically exist in the

databasedatabase Presents data in a different format Presents data in a different format

from underlying tablesfrom underlying tables Uses:Uses:

SecuritySecurity Simplifying complex queriesSimplifying complex queries

Database ViewsDatabase Views

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

Simple Views Simple Views and Complex Viewsand Complex Views

Simple Views Simple Views and Complex Viewsand Complex Views

Feature Simple ViewsComplex Views

Number of tables One One or more

Contain functions No Yes

Contain groups of data No Yes

DML through view Yes Not always

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

Creating a ViewCreating a ViewCreating a ViewCreating 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_nameAS subquery;

CREATE [OR REPLACE] VIEW view_nameAS subquery;

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

Creating a ViewCreating a ViewCreating a ViewCreating a View Create a view, EMPVU10, that contains Create a view, EMPVU10, that contains

details of employees in department 10.details of employees in department 10.

Create a view, EMPVU10, that contains Create a view, EMPVU10, that contains details of employees in department 10.details of employees in department 10.

• Describe the structure of the view by using the SQL*Plus DESCRIBE command.

• Describe the structure of the view by using the SQL*Plus DESCRIBE command.

SQL> DESCRIBE empvu10SQL> DESCRIBE empvu10

SQL> CREATE VIEW empvu10 2 AS SELECT empno, ename, job 3 FROM emp 4 WHERE deptno = 10;View created.View created.

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

Retrieving Data from a Retrieving Data from a ViewView

Retrieving Data from a Retrieving Data from a ViewView

EMPLOYEE_NUMBER NAME SALARY--------------- ---------- --------- 7698 BLAKE 2850 7654 MARTIN 1250 7499 ALLEN 1600 7844 TURNER 1500 7900 JAMES 950 7521 WARD 1250

6 rows selected.

EMPLOYEE_NUMBER NAME SALARY--------------- ---------- --------- 7698 BLAKE 2850 7654 MARTIN 1250 7499 ALLEN 1600 7844 TURNER 1500 7900 JAMES 950 7521 WARD 1250

6 rows selected.

SQL> SELECT * 2 FROM salvu30;

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

Removing a ViewRemoving a ViewRemoving a ViewRemoving a View

Remove a view without losing data Remove a view without losing data because a view is based on because a view is based on underlying tables in the database.underlying tables in the database.

Remove a view without losing data Remove a view without losing data because a view is based on because a view is based on underlying tables in the database.underlying tables in the database.

SQL> DROP VIEW empvu10; View dropped.View dropped.

DROP VIEW view; DROP VIEW view;

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

Performs set operations on outputs Performs set operations on outputs of two unrelated queriesof two unrelated queries

Both queries must have:Both queries must have: same number of display fieldssame number of display fields corresponding display fields must have corresponding display fields must have

same data typesame data type

Using Set Operators in Using Set Operators in QueriesQueries

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

UNION: combines results, UNION: combines results, suppresses duplicate rowssuppresses duplicate rows

UNION ALL: combines results, UNION ALL: combines results, displays duplicatesdisplays duplicates

INTERSECT: finds matching rowsINTERSECT: finds matching rows MINUS: returns the difference MINUS: returns the difference

between returned record setsbetween returned record sets

Query Set OperatorsQuery Set Operators

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

SynonymsSynonyms

Alternate name for a tableAlternate name for a table Allows you to not have to preface Allows you to not have to preface

table with owner’s username when table with owner’s username when you are querying a table that you are querying a table that belongs to another userbelongs to another user

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

Public SynonymsPublic Synonyms

Can only be created by a DBACan only be created by a DBA Syntax:Syntax:CREATE PUBLIC SYNONYM synonym_nameCREATE PUBLIC SYNONYM synonym_name

FOR owner_name.tablename;FOR owner_name.tablename;

All users with privileges to use table All users with privileges to use table can then use synonym instead of can then use synonym instead of owner_name.tablenameowner_name.tablename

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

Private SynonymsPrivate Synonyms

You can create private synonyms for You can create private synonyms for any tables that you have privileges any tables that you have privileges to useto use

Only you can use the synonymOnly you can use the synonym Syntax:Syntax:CREATE SYNONYM synonym_nameCREATE SYNONYM synonym_name

FOR table_name.table_name;FOR table_name.table_name;