Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

53
Bordoloi and Bordoloi and Bock Bock Copyright 2004 Prentice Hall, Inc. 7-1 COS 346 COS 346 Day 16 Day 16
  • date post

    20-Dec-2015
  • Category

    Documents

  • view

    217
  • download

    0

Transcript of Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Page 1: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-1

COS 346COS 346

Day 16Day 16

Page 2: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-2

AgendaAgenda• Assignment 6 Due Assignment 6 Due • Assignment 7 PostedAssignment 7 Posted

– Due April 5Due April 5– 4 (5?) more to go4 (5?) more to go

• Quiz 2 will April 13 (Friday the 13Quiz 2 will April 13 (Friday the 13th)th)

– DP 7 & 8, SQL 2-10DP 7 & 8, SQL 2-10– There will only be 3 exams (3 @ 10% instead of 4 @ 7.5%) There will only be 3 exams (3 @ 10% instead of 4 @ 7.5%)

• Capstone Progress Reports Due April 5Capstone Progress Reports Due April 5• Make sure to check corrections for Oracle text for WebCTMake sure to check corrections for Oracle text for WebCT

– Miss wording of Q 14 on page 89Miss wording of Q 14 on page 89• Today we will discussToday we will discuss

– Subqueries Subqueries – Lots of Hands-on stuffLots of Hands-on stuff

• We will be in the Oracle SQL text for the next 2+ weeksWe will be in the Oracle SQL text for the next 2+ weeks

Page 3: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-3

CHAPTER 7:CHAPTER 7:SUBQUERIESSUBQUERIES

Page 4: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-4

SUBQUERYSUBQUERY

• A A subquerysubquery is a query within a query. is a query within a query.

• Subqueries enable you to write queries that Subqueries enable you to write queries that select data rows for criteria that are actually select data rows for criteria that are actually developed while the query is executing at developed while the query is executing at run timerun time..

Page 5: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-5

ExampleExample

SELECT emp_last_name "Last Name", SELECT emp_last_name "Last Name", emp_first_name "First Name",emp_first_name "First Name",

emp_salary "Salary"emp_salary "Salary"FROM employeeFROM employeeWHERE emp_salary = WHERE emp_salary = (SELECT MIN(emp_salary)(SELECT MIN(emp_salary) FROM employee);FROM employee);Last Name First Name SalaryLast Name First Name Salary--------------- --------------- ----------------------- --------------- --------Markis Marcia $25,000Markis Marcia $25,000Amin Hyder $25,000Amin Hyder $25,000Prescott Sherri $25,000Prescott Sherri $25,000

Page 6: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-6

SUBQUERY TYPESSUBQUERY TYPES

• There are three basic types of subqueries. We There are three basic types of subqueries. We will study each of these in the remainder of this will study each of these in the remainder of this chapter.chapter.

1.1. Subqueries that operate on lists by use of the IN Subqueries that operate on lists by use of the IN operator or with a comparison operator modified operator or with a comparison operator modified by the ANY or ALL optional keywords. These by the ANY or ALL optional keywords. These subqueries can return a group of values, but the subqueries can return a group of values, but the values must be from a single column of a table. values must be from a single column of a table. In other words, the SELECT clause of the In other words, the SELECT clause of the subquery must contain subquery must contain only one expression or only one expression or column namecolumn name..

Page 7: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-7

SUBQUERY TYPESSUBQUERY TYPES

2.2. Subqueries that use an unmodified comparison Subqueries that use an unmodified comparison operator (=, <, >, <>) – these subqueries must operator (=, <, >, <>) – these subqueries must return only a single, return only a single, scalarscalar value. value.

3.3. Subqueries that use the EXISTS operator to test Subqueries that use the EXISTS operator to test the the existenceexistence of data rows satisfying specified of data rows satisfying specified criteria.criteria.

Page 8: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-8

SUBQUERY – General RulesSUBQUERY – General Rules

• A subquery SELECT statement is very similar to A subquery SELECT statement is very similar to the SELECT statement used to begin a regular the SELECT statement used to begin a regular or outer query. The complete syntax of a or outer query. The complete syntax of a subquery is shown below.subquery is shown below.

( SELECT [DISTINCT] subquery_select_list( SELECT [DISTINCT] subquery_select_list

FROM {table_name | view_name}FROM {table_name | view_name}

{table_name | view_name} {table_name | view_name} ......

[WHERE search_conditions][WHERE search_conditions]

[GROUP BY aggregate_expression [, [GROUP BY aggregate_expression [, aggregate_expression] aggregate_expression] ......]]

[HAVING search_conditions] )[HAVING search_conditions] )

Page 9: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-9

Rules Cont’dRules Cont’d

• The SELECT clause of a subquery must The SELECT clause of a subquery must contain only one expression, only one contain only one expression, only one aggregate function, or only one column aggregate function, or only one column name. name.

• The value(s) returned by a subquery must The value(s) returned by a subquery must be be join-compatiblejoin-compatible with the WHERE with the WHERE clause of the outer query. clause of the outer query.

Page 10: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-10

ExampleExample

SELECT emp_last_name "Last Name",SELECT emp_last_name "Last Name",

emp_first_name "First Name"emp_first_name "First Name"

FROM employeeFROM employee

WHERE emp_ssn IN WHERE emp_ssn IN

(SELECT dep_emp_ssn (SELECT dep_emp_ssn

FROM dependent);FROM dependent);

Last Name First NameLast Name First Name

------------- ---------------------------- ---------------

Bock DouglasBock Douglas

Zhu WaimanZhu Waiman

Joyner SuzanneJoyner Suzanne

Page 11: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-11

Rules Cont’dRules Cont’d

• In addition to concerns about the domain of In addition to concerns about the domain of values returned from a subquery, the data type of values returned from a subquery, the data type of the returned column value(s) must be the returned column value(s) must be join-join-compatiblecompatible. .

• Join-compatible data types are data types that Join-compatible data types are data types that the Oracle Server will convert automatically the Oracle Server will convert automatically when matching data in criteria conditions. when matching data in criteria conditions.

Page 12: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-12

Rules Cont’dRules Cont’d

• The Oracle Server will automatically The Oracle Server will automatically convert among any of the following ANSI convert among any of the following ANSI numeric data types when making numeric data types when making comparisons of numeric values because comparisons of numeric values because they all map into the Oracle NUMBER they all map into the Oracle NUMBER data type.data type.

• int (integer)int (integer)• smallint (small integer)smallint (small integer)• decimal decimal • floatfloat

Page 13: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-13

Rules Cont’dRules Cont’d

• Oracle does not make comparisons based Oracle does not make comparisons based on column names.on column names.

• Columns from two tables that are being Columns from two tables that are being compared may have different names as compared may have different names as long as they have a shared domain and the long as they have a shared domain and the same data type or convertible data types. same data type or convertible data types.

Page 14: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-14

Rules Cont’dRules Cont’d

There are additional restrictions for subqueries. There are additional restrictions for subqueries.

• The DISTINCT keyword The DISTINCT keyword cannotcannot be used in be used in subqueries that include a GROUP BY clause. subqueries that include a GROUP BY clause.

• Subqueries cannot manipulate their results Subqueries cannot manipulate their results internally. This means that a subquery cannot internally. This means that a subquery cannot include the ORDER BY clause, the COMPUTE include the ORDER BY clause, the COMPUTE clause, or the INTO keyword.clause, or the INTO keyword.

Page 15: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-15

SUBQUERIES and the IN OperatorSUBQUERIES and the IN Operator

• Subqueries that are introduced with the Subqueries that are introduced with the keyword keyword ININ take the general form: take the general form:– WHERE expression [NOT] IN (subquery)WHERE expression [NOT] IN (subquery)

• The only difference in the use of the IN The only difference in the use of the IN operator with subqueries is that the list does operator with subqueries is that the list does not consist of not consist of hard-codedhard-coded values. values.

Page 16: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-16

ExampleExample

SELECT emp_last_name "Last Name",SELECT emp_last_name "Last Name", emp_first_name "First Name"emp_first_name "First Name"FROM employeeFROM employeeWHERE emp_ssn IN WHERE emp_ssn IN (SELECT dep_emp_ssn(SELECT dep_emp_ssn FROM dependentFROM dependent WHERE dep_gender = 'M');WHERE dep_gender = 'M');

Last Name First NameLast Name First Name--------------- ------------------------------ ---------------Bock DouglasBock DouglasZhu WaimanZhu WaimanJoyner SuzanneJoyner Suzanne

Page 17: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-17

SUBQUERIES and the IN OperatorSUBQUERIES and the IN Operator

• Conceptually, this statement is evaluated in two Conceptually, this statement is evaluated in two steps.steps.

• First, the inner query returns the identification First, the inner query returns the identification numbers of those employees that have male numbers of those employees that have male dependents.dependents.

SELECT dep_emp_ssnSELECT dep_emp_ssnFROM dependentFROM dependentWHERE dep_gender = 'M';WHERE dep_gender = 'M';DEP_EMP_SDEP_EMP_S------------------999444444999444444999555555999555555999111111999111111

Page 18: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-18

SUBQUERIES and the IN OperatorSUBQUERIES and the IN Operator

• Next, these social security number values are Next, these social security number values are substituted into the outer query as the listing that substituted into the outer query as the listing that is the object of the IN operator. So, from a is the object of the IN operator. So, from a conceptual perspective, the outer query now conceptual perspective, the outer query now looks like the following:looks like the following:

SELECT emp_last_name "Last Name", SELECT emp_last_name "Last Name", emp_first_name "First Name"emp_first_name "First Name"FROM employeeFROM employeeWHERE emp_ssn IN (999444444, 999555555, 999111111);WHERE emp_ssn IN (999444444, 999555555, 999111111);Last Name First NameLast Name First Name--------------- ------------------------------ ---------------Joyner SuzanneJoyner SuzanneZhu WaimanZhu WaimanBock DouglasBock Douglas

Page 19: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-19

The NOT IN OperatorThe NOT IN Operator

• Like the IN operator, the NOT IN operator can take the Like the IN operator, the NOT IN operator can take the result of a subquery as the operator object. result of a subquery as the operator object.

SELECT emp_last_name "Last Name", emp_first_name "First SELECT emp_last_name "Last Name", emp_first_name "First Name"Name"

FROM employeeFROM employee

WHERE emp_ssn NOT IN WHERE emp_ssn NOT IN

(SELECT dep_emp_ssn(SELECT dep_emp_ssn

FROM dependent);FROM dependent);

Last Name First NameLast Name First Name

--------------- ------------------------------ ---------------

Bordoloi BijoyBordoloi Bijoy

Markis MarciaMarkis Marcia

Amin HyderAmin Hyder

more rows are displayed . . .more rows are displayed . . .

Page 20: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-20

The NOT IN OperatorThe NOT IN Operator

• The subquery shown above produces an The subquery shown above produces an intermediate result table containing the social intermediate result table containing the social security numbers of employees who have security numbers of employees who have dependents in the dependent table.dependents in the dependent table.

• Conceptually, the outer query compares each row Conceptually, the outer query compares each row of the employee table against the result table. If of the employee table against the result table. If the employee social security number is the employee social security number is NOTNOT found in the result table produced by the inner found in the result table produced by the inner query, then it is included in the final result table.query, then it is included in the final result table.

Page 21: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-21

MULTIPLE LEVELS OF NESTINGMULTIPLE LEVELS OF NESTING

• Subqueries may themselves contain subqueries. Subqueries may themselves contain subqueries. • When the WHERE clause of a subquery has as its When the WHERE clause of a subquery has as its

object another subquery, these are termed object another subquery, these are termed nested nested subqueriessubqueries. .

• Oracle places no practical limit on the number of Oracle places no practical limit on the number of queries that can be nested in a WHERE clause.queries that can be nested in a WHERE clause.

• Consider the problem of producing a listing of Consider the problem of producing a listing of employees that worked more than 10 hours on the employees that worked more than 10 hours on the project named project named Order EntryOrder Entry. .

Page 22: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-22

ExampleExample

SELECT emp_last_name "Last Name", SELECT emp_last_name "Last Name", emp_first_name "First Name"emp_first_name "First Name"FROM employeeFROM employeeWHERE emp_ssn INWHERE emp_ssn IN

(SELECT work_emp_ssn (SELECT work_emp_ssn FROM assignmentFROM assignment WHERE work_hours > 10 AND work_pro_number IN WHERE work_hours > 10 AND work_pro_number IN (SELECT pro_number(SELECT pro_number FROM projectFROM project WHERE pro_name = 'Order Entry') );WHERE pro_name = 'Order Entry') );Last Name First NameLast Name First Name--------------- ------------------------------ ---------------Bock DouglasBock DouglasPrescott SherriPrescott Sherri

Page 23: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-23

Understanding SUBQUERIESUnderstanding SUBQUERIES

• In order to understand how this query executes, In order to understand how this query executes, we begin our examination with the lowest we begin our examination with the lowest subquery.subquery.

• We will execute it independently of the outer We will execute it independently of the outer queries.queries.

SELECT pro_numberSELECT pro_number

FROM projectFROM project

WHERE pro_name = 'Order Entry';WHERE pro_name = 'Order Entry';

PRO_NUMBERPRO_NUMBER

--------------------

11

Page 24: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-24

Understanding SUBQUERIESUnderstanding SUBQUERIES

• Now, let's substitute the project number into the Now, let's substitute the project number into the IN operator list for the intermediate subquery and IN operator list for the intermediate subquery and execute it. execute it.

• The intermediate result table lists two employee The intermediate result table lists two employee social security numbers for employees that worked social security numbers for employees that worked more than 10 hours on project #1.more than 10 hours on project #1.

SELECT work_emp_ssn SELECT work_emp_ssn FROM assignmentFROM assignmentWHERE work_hours > 10 AND work_pro_number IN (1);WHERE work_hours > 10 AND work_pro_number IN (1);WORK_EMP_SSNWORK_EMP_SSN----------------------------------------------999111111999111111999888888999888888

Page 25: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-25

Understanding SUBQUERIESUnderstanding SUBQUERIES

• Finally, we will substitute these two social Finally, we will substitute these two social security numbers into the IN operator listing for security numbers into the IN operator listing for the outer query in place of the subquery. the outer query in place of the subquery.

SELECT emp_last_name "Last Name",SELECT emp_last_name "Last Name",

emp_first_name "First Name"emp_first_name "First Name"

FROM employeeFROM employee

WHERE emp_ssn IN (999111111, 999888888);WHERE emp_ssn IN (999111111, 999888888);

Last Name First NameLast Name First Name

--------------- ------------------------------ ---------------

Bock DouglasBock Douglas

Prescott SherriPrescott Sherri

Page 26: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-26

SUBQUERIES AND COMPARISON SUBQUERIES AND COMPARISON OPERATORSOPERATORS

• The general form of the WHERE clause with a The general form of the WHERE clause with a comparison operator is similar to that used thus far comparison operator is similar to that used thus far in the text.in the text.

• Note that the subquery is again enclosed by Note that the subquery is again enclosed by parentheses. parentheses.

WHERE <expression> <comparison_operator> (subquery)WHERE <expression> <comparison_operator> (subquery)

Page 27: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-27

SUBQUERIES AND COMPARISON SUBQUERIES AND COMPARISON OPERATORSOPERATORS

• The most important point to remember when using The most important point to remember when using a subquery with a comparison operator is that the a subquery with a comparison operator is that the subquery can only return a single or subquery can only return a single or scalarscalar value. value.

• This is also termed a This is also termed a scalar subqueryscalar subquery because a because a single column of a single row is returned by the single column of a single row is returned by the subquery. subquery.

• If a subquery returns more than one value, the If a subquery returns more than one value, the Oracle Server will generate the “ORA-01427: Oracle Server will generate the “ORA-01427: single-row subquery returns more than one row”single-row subquery returns more than one row” error message, and the query will fail to execute. error message, and the query will fail to execute.

Page 28: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-28

SUBQUERIES AND COMPARISON SUBQUERIES AND COMPARISON OPERATORSOPERATORS

• Let's examine a subquery that will not execute because it Let's examine a subquery that will not execute because it violates the "single value" rule. violates the "single value" rule.

• The query shown below returns multiple values for the The query shown below returns multiple values for the emp_salaryemp_salary column. column.

SELECT emp_salarySELECT emp_salary

FROM employeeFROM employeeWHERE emp_salary > 40000;WHERE emp_salary > 40000;

EMP_SALARYEMP_SALARY

--------------------------------------

5500055000

4300043000

4300043000

Page 29: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-29

SUBQUERIES AND COMPARISON SUBQUERIES AND COMPARISON OPERATORSOPERATORS

• If we substitute this query as a subquery in another If we substitute this query as a subquery in another SELECT statement, then that SELECT statement will fail. SELECT statement, then that SELECT statement will fail.

• This is demonstrated in the next SELECT statement. Here This is demonstrated in the next SELECT statement. Here the SQL code will fail because the subquery uses the the SQL code will fail because the subquery uses the greater than (>) comparison operator and the subquery greater than (>) comparison operator and the subquery returns multiple values.returns multiple values.

SELECT emp_ssnSELECT emp_ssnFROM employeeFROM employee

WHERE emp_salary > WHERE emp_salary > (SELECT emp_salary(SELECT emp_salary FROM employeeFROM employee

WHERE emp_salary > 40000); WHERE emp_salary > 40000);ERROR at line 4:ERROR at line 4:ORA-01427: single-row subquery returns more than one rowORA-01427: single-row subquery returns more than one row

Page 30: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-30

Aggregate Functions and Comparison Aggregate Functions and Comparison OperatorsOperators

• The aggregate functions (AVG, SUM, MAX, The aggregate functions (AVG, SUM, MAX, MIN, and COUNT) always return a MIN, and COUNT) always return a scalarscalar result result table.table.

• Thus, a subquery with an aggregate function as the Thus, a subquery with an aggregate function as the object of a comparison operator will always object of a comparison operator will always execute provided you have formulated the query execute provided you have formulated the query properly. properly.

Page 31: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-31

Aggregate Functions and Comparison Aggregate Functions and Comparison OperatorsOperators

SELECT emp_last_name "Last Name",SELECT emp_last_name "Last Name", emp_first_name "First Name", emp_first_name "First Name", emp_salary "Salary"emp_salary "Salary"FROM employeeFROM employeeWHERE emp_salary >WHERE emp_salary >

(SELECT AVG(emp_salary) (SELECT AVG(emp_salary) FROM employee); FROM employee);

Last Name First Name SalaryLast Name First Name Salary--------------- --------------- ------------------------- --------------- ----------Bordoloi Bijoy $55,000Bordoloi Bijoy $55,000Joyner Suzanne $43,000Joyner Suzanne $43,000Zhu Waiman $43,000Zhu Waiman $43,000Joshi Dinesh $38,000Joshi Dinesh $38,000

Page 32: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-32

Comparison Operators Modified with the Comparison Operators Modified with the ALL or ANY KeywordsALL or ANY Keywords

• The ALL and ANY keywords can modify a The ALL and ANY keywords can modify a comparison operator to allow an outer query to comparison operator to allow an outer query to accept multiple values from a subquery. accept multiple values from a subquery.

• The general form of the WHERE clause for this The general form of the WHERE clause for this type of query is shown here. type of query is shown here.

WHERE <expression> <comparison_operator> [ALL | WHERE <expression> <comparison_operator> [ALL | ANY] (subquery)ANY] (subquery)

• Subqueries that use these keywords may also Subqueries that use these keywords may also include GROUP BY and HAVING clauses. include GROUP BY and HAVING clauses.

Page 33: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-33

The ALL KeywordThe ALL Keyword

• The ALL keyword modifies the greater than The ALL keyword modifies the greater than comparison operator to mean greater than comparison operator to mean greater than allall values. values.

SELECT emp_last_name "Last Name",SELECT emp_last_name "Last Name",

emp_first_name "First Name",emp_first_name "First Name",

emp_salary "Salary"emp_salary "Salary"

FROM employeeFROM employee

WHERE emp_salary > ALLWHERE emp_salary > ALL

(SELECT emp_salary(SELECT emp_salary FROM employee FROM employee WHERE emp_dpt_number = 7); WHERE emp_dpt_number = 7);

Last Name First Name SalaryLast Name First Name Salary

--------------- --------------- ----------------------- --------------- --------

Bordoloi Bijoy $55,000Bordoloi Bijoy $55,000

Page 34: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-34

The ANY KeywordThe ANY Keyword

• The ANY keyword is not as restrictive as the The ANY keyword is not as restrictive as the ALL keyword. ALL keyword.

• When used with the greater than comparison When used with the greater than comparison operator, "> ANY" means greater than operator, "> ANY" means greater than somesome value. value.

Page 35: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-35

ExampleExample

SELECT emp_last_name "Last Name", SELECT emp_last_name "Last Name", emp_first_name "First Name",emp_first_name "First Name", emp_salary "Salary"emp_salary "Salary"FROM employeeFROM employeeWHERE emp_salary > ANYWHERE emp_salary > ANY (SELECT emp_salary(SELECT emp_salary

FROM employee FROM employee WHERE emp_salary > 30000); WHERE emp_salary > 30000);

Last Name First Name SalaryLast Name First Name Salary--------------- --------------- ----------------------- --------------- --------Bordoloi Bijoy $55,000Bordoloi Bijoy $55,000Joyner Suzanne $43,000Joyner Suzanne $43,000Zhu Waiman $43,000Zhu Waiman $43,000

Page 36: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-36

An "= ANY" (Equal Any) ExampleAn "= ANY" (Equal Any) Example• The "= ANY" operator is exactly equivalent toThe "= ANY" operator is exactly equivalent to the IN operator. the IN operator. • For example, to find the names of employees that have male For example, to find the names of employees that have male

dependents, you can use either IN or "= ANY" – both of the dependents, you can use either IN or "= ANY" – both of the queries shown below will produce an identical result table.queries shown below will produce an identical result table.

SELECT emp_last_name "Last Name", emp_first_name "First Name"SELECT emp_last_name "Last Name", emp_first_name "First Name"FROM employeeFROM employeeWHERE emp_ssn WHERE emp_ssn ININ (SELECT dep_emp_ssn(SELECT dep_emp_ssn FROM dependentFROM dependent WHERE dep_gender = 'M');WHERE dep_gender = 'M');

SELECT emp_last_name "Last Name", emp_first_name "First Name"SELECT emp_last_name "Last Name", emp_first_name "First Name"FROM employeeFROM employeeWHERE emp_ssn WHERE emp_ssn = ANY= ANY (SELECT dep_emp_ssn(SELECT dep_emp_ssn FROM dependentFROM dependent WHERE dep_gender = 'M');WHERE dep_gender = 'M');

Page 37: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-37

An "= ANY" (Equal Any) ExampleAn "= ANY" (Equal Any) Example

• OUTPUTOUTPUT

Last Name First NameLast Name First Name

--------------- ------------------------------ ---------------

Bock DouglasBock Douglas

Zhu WaimanZhu Waiman

Joyner SuzanneJoyner Suzanne

Page 38: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-38

An "!= ANY" (Not Equal Any) ExampleAn "!= ANY" (Not Equal Any) Example

• The "= ANY" is identical to the IN operator.The "= ANY" is identical to the IN operator.• However, the "!= ANY" (not equal any) is However, the "!= ANY" (not equal any) is notnot equivalent equivalent

to the NOT IN operator.to the NOT IN operator.• If a subquery of employee salaries produces an If a subquery of employee salaries produces an

intermediate result table with the salaries $38,000, intermediate result table with the salaries $38,000, $43,000, and $55,000, then the WHERE clause shown $43,000, and $55,000, then the WHERE clause shown here means "NOT $38,000" AND "NOT $43,000" AND here means "NOT $38,000" AND "NOT $43,000" AND "NOT $55,000"."NOT $55,000".

WHERE NOT IN (38000, 43000, 55000);WHERE NOT IN (38000, 43000, 55000);

• However, the "!= ANY" comparison operator and keyword However, the "!= ANY" comparison operator and keyword combination shown in this next WHERE clause means combination shown in this next WHERE clause means "NOT $38,000" OR "NOT $43,000" OR "NOT $55,000"."NOT $38,000" OR "NOT $43,000" OR "NOT $55,000".

Page 39: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-39

CORRELATED SUBQUERIESCORRELATED SUBQUERIES

• A A correlated subquerycorrelated subquery is one where the inner is one where the inner query depends on values provided by the outer query depends on values provided by the outer query. query.

• This means the inner query is executed repeatedly, This means the inner query is executed repeatedly, once for each row that might be selected by the once for each row that might be selected by the outer query.outer query.

Page 40: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-40

CORRELATED SUBQUERIESCORRELATED SUBQUERIES

SELECT emp_last_name "Last Name",SELECT emp_last_name "Last Name", emp_first_name "First Name",emp_first_name "First Name", emp_dpt_number "Dept",emp_dpt_number "Dept", emp_salary "Salary"emp_salary "Salary"FROM employee e1 WHERE emp_salary =FROM employee e1 WHERE emp_salary = (SELECT MAX(emp_salary)(SELECT MAX(emp_salary) FROM employeeFROM employee WHERE emp_dpt_number = WHERE emp_dpt_number = e1.emp_dpt_number);e1.emp_dpt_number);

  

Page 41: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-41

CORRELATED SUBQUERIESCORRELATED SUBQUERIES

• OutputOutput

Last Name FirstName Dept SalaryLast Name FirstName Dept Salary---------- ---------- ----- ------------------ ---------- ----- --------Bordoloi Bijoy 1 $55,000Bordoloi Bijoy 1 $55,000Joyner Suzanne 3 $43,000Joyner Suzanne 3 $43,000Zhu Waiman 7 $43,000Zhu Waiman 7 $43,000

Page 42: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-42

CORRELATED SUBQUERIESCORRELATED SUBQUERIES

• The subquery in this SELECT statement The subquery in this SELECT statement cannot be resolved independently of the cannot be resolved independently of the main query. main query.

• Notice that the outer query specifies that Notice that the outer query specifies that rows are selected from the rows are selected from the employeeemployee table table with an alias name of with an alias name of e1e1. .

• The inner query compares the employee The inner query compares the employee department number column department number column ((emp_dpt_numberemp_dpt_number) of the ) of the employeeemployee table to table to the same column for the alias table name the same column for the alias table name e1e1..

Page 43: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-43

CORRELATED SUBQUERIESCORRELATED SUBQUERIES

• The value of The value of e1.emp_dpt_numbere1.emp_dpt_number is treated like a is treated like a variable – it changes as the Oracle Server variable – it changes as the Oracle Server examines each row of the employee table.examines each row of the employee table.

• The subquery's results are correlated with each The subquery's results are correlated with each individual row of the main query – thus, the term individual row of the main query – thus, the term correlated subquerycorrelated subquery..

Page 44: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-44

Subqueries and the EXISTS OperatorSubqueries and the EXISTS Operator

• When a subquery uses the EXISTS operator, When a subquery uses the EXISTS operator, the subquery functions as an the subquery functions as an existenceexistence testtest. .

• The WHERE clause of the outer query tests The WHERE clause of the outer query tests for the existence of rows returned by the for the existence of rows returned by the inner query.inner query.

• The subquery does not actually produce any The subquery does not actually produce any data; rather, it returns a value of TRUE or data; rather, it returns a value of TRUE or FALSE. FALSE.

Page 45: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-45

Subqueries and the EXISTS OperatorSubqueries and the EXISTS Operator

• The general format of a subquery WHERE The general format of a subquery WHERE clause with an EXISTS operator is shown clause with an EXISTS operator is shown here.here.

• Note that the NOT operator can also be used Note that the NOT operator can also be used to negate the result of the EXISTS operator.to negate the result of the EXISTS operator.

WHERE [NOT] EXISTS (subquery)WHERE [NOT] EXISTS (subquery)

Page 46: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-46

ExampleExample

SELECT emp_last_name "Last Name", SELECT emp_last_name "Last Name", emp_first_name "First Name"emp_first_name "First Name"

FROM employeeFROM employeeWHERE EXISTSWHERE EXISTS (SELECT *(SELECT * FROM dependentFROM dependent WHERE emp_ssn = dep_emp_ssn);WHERE emp_ssn = dep_emp_ssn);

Last Name First NameLast Name First Name---------- ------------------------- ---------------Joyner SuzanneJoyner SuzanneZhu WaimanZhu WaimanBock DouglasBock Douglas

Page 47: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-47

Subqueries and the EXISTS OperatorSubqueries and the EXISTS Operator

• Subqueries using an EXISTS operator are a bit Subqueries using an EXISTS operator are a bit different from other subqueries, in the following different from other subqueries, in the following ways:ways:

1.1. The keyword EXISTS is not preceded by a The keyword EXISTS is not preceded by a column name, constant, or other expression.column name, constant, or other expression.

2.2. The SELECT clause list of a subquery that uses The SELECT clause list of a subquery that uses an EXISTS operator almost always consists of an EXISTS operator almost always consists of an asterisk (*). This is because there is no real an asterisk (*). This is because there is no real point in listing column names since you are point in listing column names since you are simply testing for the existence of rows that simply testing for the existence of rows that meet the conditions specified in the subquery. meet the conditions specified in the subquery.

Page 48: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-48

Subqueries and the EXISTS OperatorSubqueries and the EXISTS Operator

3.3. The subquery evaluates to TRUE or FALSE The subquery evaluates to TRUE or FALSE rather than returning any data.rather than returning any data.

4.4. A subquery that uses an EXISTS operator A subquery that uses an EXISTS operator will always be a correlated subquery.will always be a correlated subquery.

Page 49: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-49

Subqueries and the EXISTS OperatorSubqueries and the EXISTS Operator

• The EXISTS operator is very important, The EXISTS operator is very important, because there is often no alternative to its use.because there is often no alternative to its use.

• All queries that use the IN operator or a All queries that use the IN operator or a modified comparison operator (=, <, >, etc. modified comparison operator (=, <, >, etc. modified by ANY or ALL) can be expressed modified by ANY or ALL) can be expressed with the EXISTS operator.with the EXISTS operator.

• However, some queries formulated with However, some queries formulated with EXISTS cannot be expressed in any other EXISTS cannot be expressed in any other way! way!

Page 50: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-50

Subqueries and the EXISTS OperatorSubqueries and the EXISTS Operator

SELECT emp_last_nameSELECT emp_last_nameFROM employeeFROM employeeWHERE emp_ssn = ANYWHERE emp_ssn = ANY (SELECT dep_emp_ssn(SELECT dep_emp_ssn FROM dependent);FROM dependent);    

EMP_LAST_NAMEEMP_LAST_NAME--------------------------BockBockZhuZhuJoynerJoyner

SELECT emp_last_nameSELECT emp_last_nameFROM employeeFROM employeeWHERE EXISTSWHERE EXISTS (SELECT *(SELECT * FROM dependentFROM dependent WHERE emp_ssn = WHERE emp_ssn =

dep_emp_ssn);dep_emp_ssn);  EMP_LAST_NAMEEMP_LAST_NAME--------------------------------BockBockZhuZhuJoynerJoyner

Page 51: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-51

Subqueries and the EXISTS OperatorSubqueries and the EXISTS Operator

• The NOT EXISTS operator is the The NOT EXISTS operator is the mirror-image of the EXISTS operator.mirror-image of the EXISTS operator.

• A query that uses NOT EXISTS in the A query that uses NOT EXISTS in the WHERE clause is satisfied if the WHERE clause is satisfied if the subquery returns subquery returns nono rows. rows.

Page 52: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-52

Subqueries and the ORDER BY ClauseSubqueries and the ORDER BY Clause • The SELECT statement shown below adds the The SELECT statement shown below adds the

ORDER BY clause to specify sorting by first ORDER BY clause to specify sorting by first name within last name.name within last name.

• Note that the ORDER BY clause is placed after Note that the ORDER BY clause is placed after the WHERE clause, and that this includes the the WHERE clause, and that this includes the subquery as part of the WHERE clause. subquery as part of the WHERE clause.

SELECT emp_last_name "Last Name",SELECT emp_last_name "Last Name", emp_first_name "First Name"emp_first_name "First Name"FROM employeeFROM employeeWHERE EXISTSWHERE EXISTS (SELECT *(SELECT * FROM dependentFROM dependent WHERE emp_ssn = dep_emp_ssn)WHERE emp_ssn = dep_emp_ssn)ORDER BY emp_last_name, emp_first_name;ORDER BY emp_last_name, emp_first_name;

Page 53: Bordoloi and BockCopyright 2004 Prentice Hall, Inc.7-1 COS 346 Day 16.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 7-53

Subqueries and the ORDER BY ClauseSubqueries and the ORDER BY Clause

Output:Output:

Last Name First NameLast Name First Name

---------- ------------------------- ---------------

Bock DouglasBock Douglas

Joyner SuzanneJoyner Suzanne

Zhu WaimanZhu Waiman