Bordoloi and BockCopyright 2004 Prentice Hall, Inc.5-1 COS 346 Day 15.

79
Bordoloi and Bordoloi and Bock Bock Copyright 2004 Prentice Hall, Inc. 5-1 COS 346 COS 346 Day 15 Day 15
  • date post

    20-Dec-2015
  • Category

    Documents

  • view

    215
  • download

    0

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

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

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

COS 346COS 346

Day 15Day 15

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

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

AgendaAgenda• Assignment 5 re-graded (based on extra info provided) Assignment 5 re-graded (based on extra info provided)

– 3 A’s, 1 B, 1 C’s and 1 D3 A’s, 1 B, 1 C’s and 1 D– Lots of missing data Lots of missing data

• Assignment 6 Posted Assignment 6 Posted – Due March 22 Due March 22

• Quiz 2 will April 13 (Friday the 13Quiz 2 will April 13 (Friday the 13 th)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 Over DueCapstone Progress Reports Over Due– Missing 3 Missing 3 – SQL Coding Exercises and Question on page 44SQL Coding Exercises and Question on page 44

• Today we will discus Today we will discus – Aggregate Row Functions (Chap 5)(Chap 5)– Joins (Chap 6)Joins (Chap 6)– 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.5-1 COS 346 Day 15.

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

CHAPTER 5:CHAPTER 5:AGGREGATE ROW FUNCTIONSAGGREGATE ROW FUNCTIONS

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

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

AGGREGATE ROW FUNCTIONSAGGREGATE ROW FUNCTIONS

• Aggregate Row functions give the user the Aggregate Row functions give the user the ability to answer business questions such as:ability to answer business questions such as:

What is the average salary of an employee What is the average salary of an employee in the company?in the company?

What were the total salaries for a particular What were the total salaries for a particular year?year?

What are the maximum and minimum What are the maximum and minimum salaries in the Computers Department? salaries in the Computers Department?

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

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

AGGREGATE ROW FUNCTIONSAGGREGATE ROW FUNCTIONS

• Aggregate functions perform a variety of Aggregate functions perform a variety of actions such as counting all the rows in a actions such as counting all the rows in a table, averaging a column's data, and table, averaging a column's data, and summing numeric data.summing numeric data.

• Aggregates can also search a table to find Aggregates can also search a table to find the highest "MAX" or lowest "MIN" values the highest "MAX" or lowest "MIN" values in a column. in a column.

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

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

AGGREGATE ROW FUNCTIONSAGGREGATE ROW FUNCTIONS

• List of aggregate functions including their syntax List of aggregate functions including their syntax and use.and use.

Function Syntax Function Use

SUM( [ALL | DISTINCT] expression )

The total of the (distinct) values in a numeric column/expression.

AVG( [ALL | DISTINCT] expression )

The average of the (distinct) values in a numeric column/expression.

COUNT( [ALL | DISTINCT] expression )

The number of (distinct) non-NULL values in a column/expression.

COUNT(*) The number of selected rows.

MAX(expression) The highest value in a column/expression.

MIN(expression) The lowest value in a column/expression.

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

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

AGGREGATE ROW FUNCTIONSAGGREGATE ROW FUNCTIONS

• There are two rules that you must understand and There are two rules that you must understand and follow when using aggregates: follow when using aggregates:

• Aggregate functions can be used in both the SELECT Aggregate functions can be used in both the SELECT and HAVING clauses (the HAVING clause is covered and HAVING clauses (the HAVING clause is covered later in this chapter).later in this chapter).

• Aggregate functions cannotAggregate functions cannot be used in a WHERE be used in a WHERE clause.clause.

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

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

EXAMPLEEXAMPLE

• The following query The following query is wrong and will produce is wrong and will produce the Oracle ORA-00934 the Oracle ORA-00934 group function is not group function is not allowed hereallowed here error message. error message.

SELECT *SELECT *

FROM employeeFROM employee

WHERE AVG(emp_salary) > 40000;WHERE AVG(emp_salary) > 40000;

  

ERROR at line 3: ORA-00934: group function is not ERROR at line 3: ORA-00934: group function is not allowed here.allowed here.

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

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

COUNT( )COUNT( )• If a manager needs to know how many employees work If a manager needs to know how many employees work

in the organization, COUNT(*) can be used to produce in the organization, COUNT(*) can be used to produce this information. this information.

• The COUNT(*) function counts all rows in a table. The COUNT(*) function counts all rows in a table. • The wild card asterisk (*) would be used as the The wild card asterisk (*) would be used as the

parameter in the function. parameter in the function.

SELECT COUNT(*)SELECT COUNT(*)FROM employee;FROM employee;

COUNT(*)COUNT(*) ---------------- 88  

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

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

COUNT( )COUNT( )

• The result table for the COUNT(*) function The result table for the COUNT(*) function is a single is a single scalarscalar value. value.

• Notice that the result table has a column Notice that the result table has a column heading that corresponds to the name of the heading that corresponds to the name of the aggregate function specified in the SELECT aggregate function specified in the SELECT clause. clause.

• The output column can be assigned a more The output column can be assigned a more meaningful column name as is shown in the meaningful column name as is shown in the revised query.revised query.

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

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

COUNT( )COUNT( )

• This is accomplished by simply listing the desired This is accomplished by simply listing the desired column name inside double-quotes after the column name inside double-quotes after the aggregate function specification.aggregate function specification.

SELECT COUNT(*) "Number of SELECT COUNT(*) "Number of Employees"Employees"

FROM employee;FROM employee;

Number of EmployeesNumber of Employees

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

88

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

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

COUNT( )COUNT( )

• COUNT(*) is used to count all the rows in a table.COUNT(*) is used to count all the rows in a table.• COUNT(column name) does almost the same thing. COUNT(column name) does almost the same thing.

The difference is that you may define a specific The difference is that you may define a specific column to be counted.column to be counted.

• When column name is specified in the COUNT When column name is specified in the COUNT function, rows containing a NULL value in the function, rows containing a NULL value in the specified column are omitted. specified column are omitted.

• A NULL value stands for “unknown” or A NULL value stands for “unknown” or “unknowable” and must not be confused with a blank “unknowable” and must not be confused with a blank or zero. or zero.

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

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

COUNT ( )COUNT ( )SELECT COUNT(emp_superssn) "Number Supervised SELECT COUNT(emp_superssn) "Number Supervised Employees"Employees"FROM employee;FROM employee;

Number Supervised EmployeesNumber Supervised Employees------------------------------------------------------

77

• In contrast the count(*) will count each row In contrast the count(*) will count each row regardless of NULL values.regardless of NULL values.

SELECT COUNT(*) "Number of Employees“SELECT COUNT(*) "Number of Employees“FROM employee;FROM employee;Number of EmployeesNumber of Employees--------------------------------------

88

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

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

Using the AVG FunctionUsing the AVG Function

• AVG function is used to compute the average value AVG function is used to compute the average value for the for the emp_salaryemp_salary column in the column in the employeeemployee table. table.

• For example, the following query returns the For example, the following query returns the average of the employee salaries. average of the employee salaries.

SELECT AVG(emp_salary) "Average Employee SELECT AVG(emp_salary) "Average Employee Salary"Salary"

FROM employee;FROM employee;  Average Employee SalaryAverage Employee Salary---------------------------------------------- $35,500$35,500

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

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

More ExamplesMore Examples

• What is the average salary What is the average salary offeredoffered to employees? to employees?

• This question asks you to incorporate the concept of This question asks you to incorporate the concept of computing the average of the distinct salaries paid by the computing the average of the distinct salaries paid by the organization.organization.

• The same query with the DISTINCT keyword in the The same query with the DISTINCT keyword in the aggregate function returns a different average.aggregate function returns a different average.

SELECT AVG(DISTINCT emp_salary) "Average Employee SELECT AVG(DISTINCT emp_salary) "Average Employee Salary"Salary"

FROM employee;FROM employee;

  

Average Employee SalaryAverage Employee Salary

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

$38,200$38,200

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

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

Using the SUM FunctionUsing the SUM Function

• The SUM function can compute the total of a The SUM function can compute the total of a specified table column.specified table column.

• The SELECT statement shown here will return the The SELECT statement shown here will return the total of the total of the emp_salaryemp_salary column from the column from the employeeemployee table. table.

SELECT SUM(emp_salary) "Total Salary"SELECT SUM(emp_salary) "Total Salary"

FROM employee;FROM employee;

  

Total SalaryTotal Salary

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

$284,000$284,000

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

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

More ExamplesMore Examples

• If management is preparing a budget for various If management is preparing a budget for various departments, you may be asked to write a query to departments, you may be asked to write a query to compute the total salary for different departments. compute the total salary for different departments.

• The query shown here will compute the total The query shown here will compute the total emp_salary for employees assigned to department emp_salary for employees assigned to department #7.#7.

SELECT SUM(emp_salary) "Total Salary Dept 7"SELECT SUM(emp_salary) "Total Salary Dept 7"FROM employeeFROM employeeWHERE emp_dpt_number = 7;WHERE emp_dpt_number = 7;

  Total Salary Dept 7Total Salary Dept 7--------------------------------------

$136,000$136,000

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

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

MIN and MAX FunctionsMIN and MAX Functions

• The MIN function returns the lowest value stored in The MIN function returns the lowest value stored in a data column.a data column.

• The MAX function returns the largest value stored The MAX function returns the largest value stored in a data column. in a data column.

• Unlike SUM and AVG, the MIN and MAX Unlike SUM and AVG, the MIN and MAX functions work with both numeric and character data functions work with both numeric and character data columns. columns.

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

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

ExampleExample

• A query that uses the MIN function to find the lowest value A query that uses the MIN function to find the lowest value stored in the stored in the emp_last_nameemp_last_name column of the column of the employeeemployee table. table.

• This is analogous to determine which employee's last name This is analogous to determine which employee's last name comes first in the alphabet. comes first in the alphabet.

• Conversely, MAX() will return the employee row where last Conversely, MAX() will return the employee row where last name comes last (highest) in the alphabet. name comes last (highest) in the alphabet.

SELECT MIN(emp_last_name), MAX(emp_last_name)SELECT MIN(emp_last_name), MAX(emp_last_name)

FROM employee;FROM employee;

MIN(EMP_LAST_NAME) MAX(EMP_LAST_NAME)MIN(EMP_LAST_NAME) MAX(EMP_LAST_NAME)

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

Amin ZhuAmin Zhu

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

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

ExampleExample

• More often the MIN and MAX functions are used to More often the MIN and MAX functions are used to manipulate numeric data columns. manipulate numeric data columns.

• The query shown here will use the MAX function to display The query shown here will use the MAX function to display the highest salary paid to an employee in the organizationthe highest salary paid to an employee in the organization

SELECT MAX(emp_salary) "Highest Salary"SELECT MAX(emp_salary) "Highest Salary"

FROM employee;FROM employee;

  

Highest SalaryHighest Salary

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

$55,000$55,000

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

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

Using GROUP BY with Aggregate Using GROUP BY with Aggregate FunctionsFunctions

• The power of aggregate functions is greater when The power of aggregate functions is greater when combined with the GROUP BY clause. combined with the GROUP BY clause.

• In fact, the GROUP BY clause is rarely used without In fact, the GROUP BY clause is rarely used without an aggregate function. an aggregate function.

• It is possible to use the GROUP BY clause without It is possible to use the GROUP BY clause without aggregates, but such a construction has very limited aggregates, but such a construction has very limited functionality, and could lead to a result table that is functionality, and could lead to a result table that is confusing or misleading. confusing or misleading.

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

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

ExampleExample

• The following query displays how many employees The following query displays how many employees work for each department:work for each department:

SELECT emp_dpt_number "Department",SELECT emp_dpt_number "Department",COUNT(*) "Department Count"COUNT(*) "Department Count"FROM employeeFROM employeeGROUP BY emp_dpt_number;GROUP BY emp_dpt_number;

  Department Department CountDepartment Department Count---------- -------------------------- ----------------

1 11 1 3 33 3 7 47 4  

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

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

GROUP BY ClauseGROUP BY Clause

• Some RDBM provides considerable Some RDBM provides considerable flexibility in specifying the GROUP BY flexibility in specifying the GROUP BY clause.clause.

• The column name used in a GROUP BY does The column name used in a GROUP BY does not have to be listed in the SELECT clause; not have to be listed in the SELECT clause; however, it must be a column name from one however, it must be a column name from one of the tables listed in the FROM clause. of the tables listed in the FROM clause.

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

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

ExampleExample

• We could rewrite the last query without specifying the We could rewrite the last query without specifying the emp_dpt_numberemp_dpt_number column as part of the result table, column as part of the result table, but as you can see below, the results are rather cryptic but as you can see below, the results are rather cryptic without the without the emp_dpt_numberemp_dpt_number column to identify the column to identify the meaning of the aggregate count. meaning of the aggregate count.

SELECT COUNT(*) "Department Count"SELECT COUNT(*) "Department Count"FROM employeeFROM employeeGROUP BY emp_dpt_number;GROUP BY emp_dpt_number;

   Department CountDepartment Count--------------------------------

11 33 44

  

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

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

Using GROUP BY with ExpressionsUsing GROUP BY with Expressions

• In addition to column names, any expression listed in a In addition to column names, any expression listed in a SELECT clause can be used with a GROUP BY clause.SELECT clause can be used with a GROUP BY clause.

SELECT AVG(emp_salary) "Current Average Salary", SELECT AVG(emp_salary) "Current Average Salary",

AVG(emp_salary * 1.25) "New Average Salary"AVG(emp_salary * 1.25) "New Average Salary"

FROM employeeFROM employee

GROUP BY emp_salary * 1.25;GROUP BY emp_salary * 1.25;

Current Average Salary New Average SalaryCurrent Average Salary New Average Salary

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

$25,000 $31,250$25,000 $31,250

$30,000 $37,500$30,000 $37,500

$38,000 $47,500$38,000 $47,500

$43,000 $53,750$43,000 $53,750

$55,000 $68,750$55,000 $68,750

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

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

Nesting Aggregate Functions: MAX(AVG( ))Nesting Aggregate Functions: MAX(AVG( ))

• A result table to determine which department A result table to determine which department pays employees the highest average salary would pays employees the highest average salary would be difficult. be difficult.

• This can be accomplished by nesting the This can be accomplished by nesting the AVG(salary) inside the MAX() function and AVG(salary) inside the MAX() function and removing the removing the emp_dpt_numberemp_dpt_number column from the column from the SELECT list.SELECT list.

SELECT MAX(AVG(emp_salary)) "Largest Average Salary"SELECT MAX(AVG(emp_salary)) "Largest Average Salary"FROM employeeFROM employeeGROUP BY emp_dpt_number;GROUP BY emp_dpt_number;  Largest Average SalaryLargest Average Salary-------------------------------------------- $55,000$55,000

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

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

GROUP BY and NULL ValuesGROUP BY and NULL Values

• When a query with a GROUP BY clause processes When a query with a GROUP BY clause processes data columns that contain NULL values, all data data columns that contain NULL values, all data rows containing a NULL value are placed into a rows containing a NULL value are placed into a distinct group. distinct group.

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

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

GROUP BY and NULL ValuesGROUP BY and NULL ValuesSELECT work_emp_ssn "SSN", SELECT work_emp_ssn "SSN", SUM(work_hours) "Total Hours Worked"SUM(work_hours) "Total Hours Worked"FROM assignmentFROM assignmentGROUP BY work_emp_ssn;GROUP BY work_emp_ssn;

SSN Total Hours WorkedSSN Total Hours Worked--------- --------------------------- ------------------999111111 39.9999111111 39.9999222222 39.6999222222 39.6999333333 42.1999333333 42.1999444444 44.6999444444 44.6999555555 34999555555 34999666666999666666999887777 41999887777 41999888888 43999888888 43  

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

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

Using GROUP BY with a WHERE ClauseUsing GROUP BY with a WHERE Clause• The WHERE clause works to eliminate data table rows The WHERE clause works to eliminate data table rows

from consideration before any grouping takes place. from consideration before any grouping takes place. • The query shown here produces an average hours worked The query shown here produces an average hours worked

result table for employees with a social security number result table for employees with a social security number that is larger than 999-66-0000. that is larger than 999-66-0000.

SELECT work_emp_ssn SSN, SELECT work_emp_ssn SSN, AVG(work_hours) "Average Hours Worked"AVG(work_hours) "Average Hours Worked"FROM assignment FROM assignment WHERE work_emp_ssn > 999660000WHERE work_emp_ssn > 999660000GROUP BY work_emp_ssn;GROUP BY work_emp_ssn;

  SSN Average Hours WorkedSSN Average Hours Worked--------- ----------------------------- --------------------999666666999666666999887777 20.5999887777 20.5999888888 21.5999888888 21.5

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

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

Using GROUP BY with an ORDER BY ClauseUsing GROUP BY with an ORDER BY Clause

• The ORDER BY clause allows you to specify The ORDER BY clause allows you to specify how rows in a result table are sorted. how rows in a result table are sorted.

• The default ordering is from smallest to largest The default ordering is from smallest to largest value. value.

• A GROUP BY clause in a SELECT statement A GROUP BY clause in a SELECT statement will determine the sort order of rows in a result will determine the sort order of rows in a result table.table.

• The sort order can be changed by specifying an The sort order can be changed by specifying an ORDER BY clause after the GROUP BY ORDER BY clause after the GROUP BY clause. clause.

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

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

Using GROUP BY with an ORDER BY ClauseUsing GROUP BY with an ORDER BY Clause

SELECT emp_dpt_number "Department", SELECT emp_dpt_number "Department", AVG(emp_salary) "Average Salary"AVG(emp_salary) "Average Salary"

FROM employeeFROM employee

GROUP BY emp_dpt_numberGROUP BY emp_dpt_number

ORDER BY AVG(emp_salary);ORDER BY AVG(emp_salary);

  

Department Average SalaryDepartment Average Salary

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

3 $31,0003 $31,000

7 $34,0007 $34,000

1 $55,0001 $55,000

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

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

GROUP BY with a HAVING ClauseGROUP BY with a HAVING Clause

• The HAVING clause is used for aggregate The HAVING clause is used for aggregate functions in the same way that a WHERE functions in the same way that a WHERE clause is used for column names and clause is used for column names and expressions. expressions.

• The HAVING and WHERE clauses do the The HAVING and WHERE clauses do the same thing, that is, filter rows from inclusion same thing, that is, filter rows from inclusion in a result table based on a condition.in a result table based on a condition.

• A WHERE clause is used to filter rows A WHERE clause is used to filter rows BEFOREBEFORE the GROUPING action. the GROUPING action.

• A HAVING clause filters rows A HAVING clause filters rows AFTER AFTER the the GROUPING action. GROUPING action.

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

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

GROUP BY with a HAVING ClauseGROUP BY with a HAVING Clause

SELECT emp_dpt_number "Department", SELECT emp_dpt_number "Department", AVG(emp_salary) "Average Salary"AVG(emp_salary) "Average Salary"

FROM employeeFROM employee

GROUP BY emp_dpt_numberGROUP BY emp_dpt_number

HAVING AVG(emp_salary) > 33000;HAVING AVG(emp_salary) > 33000;

  

Department Average SalaryDepartment Average Salary

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

1 $55,0001 $55,000

7 $34,0007 $34,000

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

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

Combining HAVING Clause with WHERE Clause Combining HAVING Clause with WHERE Clause

SELECT emp_dpt_number "Department", SELECT emp_dpt_number "Department", AVG(emp_salary) "Average Salary"AVG(emp_salary) "Average Salary"

FROM employeeFROM employee

WHERE emp_dpt_number <> 1WHERE emp_dpt_number <> 1

GROUP BY emp_dpt_numberGROUP BY emp_dpt_number

HAVING AVG(emp_salary) > 33000;HAVING AVG(emp_salary) > 33000;

  

Department Average SalaryDepartment Average Salary

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

7 $34,0007 $34,000

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

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

GROUP BY with a HAVING ClauseGROUP BY with a HAVING Clause

Conceptually, SQL performs the following steps in the Conceptually, SQL performs the following steps in the query given above.query given above.

1.   The WHERE clause filters rows that do not meet the 1.   The WHERE clause filters rows that do not meet the conditionconditionemp_dpt_number <>emp_dpt_number <> 1. 1.2.   The GROUP BY clause collects the surviving rows 2.   The GROUP BY clause collects the surviving rows into one or more groups for each unique into one or more groups for each unique emp_dpt_numberemp_dpt_number..3.   The aggregate function calculates the average salary 3.   The aggregate function calculates the average salary for each for each emp_dpt_numberemp_dpt_number grouping. grouping.4. The HAVING clause filters out the rows from the 4. The HAVING clause filters out the rows from the result table that do not meet the condition average salary result table that do not meet the condition average salary greater than $33,000.greater than $33,000.

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

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

Using GROUP BY with an ORDER BY ClauseUsing GROUP BY with an ORDER BY Clause

Standard SQL RulesStandard SQL Rules

The most common use of a HAVING clause is The most common use of a HAVING clause is to create result tables containing one row per to create result tables containing one row per group, with one or more summary values in the group, with one or more summary values in the row. To do this your query must meet the row. To do this your query must meet the following conditions:following conditions:

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

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

Using GROUP BY with an ORDER BY ClauseUsing GROUP BY with an ORDER BY Clause

• Columns listed in a SELECT clause must also be Columns listed in a SELECT clause must also be listed in the GROUP BY expression or they must be listed in the GROUP BY expression or they must be arguments of aggregate functions. arguments of aggregate functions.

• A GROUP BY expression can only contain column A GROUP BY expression can only contain column names that are in the SELECT clause listing.names that are in the SELECT clause listing.

• Columns in a HAVING expression must be either:Columns in a HAVING expression must be either:single-valued—arguments of an aggregate function, single-valued—arguments of an aggregate function,

for instance, or for instance, or listed in the SELECT clause listing or GROUP BY listed in the SELECT clause listing or GROUP BY

clause. clause.

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

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

ExampleExample

SELECT emp_dpt_number "Department", SELECT emp_dpt_number "Department", COUNT(*) "Department Count"COUNT(*) "Department Count"

FROM employeeFROM employeeGROUP BY emp_dpt_numberGROUP BY emp_dpt_numberHAVING COUNT(*) >= 3;HAVING COUNT(*) >= 3;  Department Department CountDepartment Department Count---------- -------------------------- ---------------- 3 33 3 7 47 4  

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

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

More ExamplesMore Examples

SELECT emp_dpt_number "Department",SELECT emp_dpt_number "Department",

COUNT(*) "Department Count",COUNT(*) "Department Count",

MAX(emp_salary) "Top Salary",MAX(emp_salary) "Top Salary",

MIN(emp_salary) "Low Salary"MIN(emp_salary) "Low Salary"

FROM employeeFROM employee

GROUP BY emp_dpt_numberGROUP BY emp_dpt_number

HAVING COUNT(*) >= 3;HAVING COUNT(*) >= 3;

Department Department Count Top Salary Low SalaryDepartment Department Count Top Salary Low Salary

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

3 3 $43,000 $25,0003 3 $43,000 $25,000

7 4 $43,000 $25,0007 4 $43,000 $25,000

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

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

SQL Extensions to GROUP BY and SQL Extensions to GROUP BY and HAVING ClausesHAVING Clauses

• Various software vendors, such as Oracle, provide extensions Various software vendors, such as Oracle, provide extensions to the standard Structured Query Language. to the standard Structured Query Language.

• A SELECT clause listing that includes aggregate functions A SELECT clause listing that includes aggregate functions can also include columns that are not arguments of aggregate can also include columns that are not arguments of aggregate functions, or that are not included in the GROUP BY clause. functions, or that are not included in the GROUP BY clause.

• The GROUP BY clause can include column names or The GROUP BY clause can include column names or expressions that are not included in the SELECT clause expressions that are not included in the SELECT clause listing.listing.

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

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

SQL Extensions to GROUP BY and SQL Extensions to GROUP BY and HAVING ClausesHAVING Clauses

• The GROUP BY ALL clause displays all groups, The GROUP BY ALL clause displays all groups, even those excluded from calculations by a even those excluded from calculations by a WHERE clause. WHERE clause.

• The HAVING clause can include columns or The HAVING clause can include columns or expressions that are not listed in the SELECT expressions that are not listed in the SELECT clause or in a GROUP BY clause. clause or in a GROUP BY clause.

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

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

GROUP BY with a HAVING ClauseGROUP BY with a HAVING Clause

• The HAVING clause is a conditional option The HAVING clause is a conditional option that is directly related to the GROUP BY that is directly related to the GROUP BY clause option because a HAVING clause clause option because a HAVING clause eliminates rows from a result table based on eliminates rows from a result table based on the result of a GROUP BY clause. the result of a GROUP BY clause.

• In Oracle, a HAVING clause will In Oracle, a HAVING clause will notnot work work without a GROUP BY clause.without a GROUP BY clause.

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

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

GROUP BY with a HAVING ClauseGROUP BY with a HAVING Clause

SELECT emp_dpt_number, SELECT emp_dpt_number, AVG(emp_salary)AVG(emp_salary)

FROM employeeFROM employee

HAVING AVG(emp_salary) > 33000;HAVING AVG(emp_salary) > 33000;

  

ERROR at line 1:ERROR at line 1:

ORA-00937: not a single-group ORA-00937: not a single-group group functiongroup function

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

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

Oracle SQL FormatOracle SQL Format

SELECT [ALL | DISTINCT] select-list FROM SELECT [ALL | DISTINCT] select-list FROM table-reference-listtable-reference-list

[WHERE [WHERE search-conditionsearch-condition] ] [GROUP BY column-name [, column-name]... ][GROUP BY column-name [, column-name]... ][HAVING [HAVING search-conditionsearch-condition] ] [[UNION | UNION ALL |INTERSECT | MINUS] [[UNION | UNION ALL |INTERSECT | MINUS]

select-statementselect-statement]... ]... [ORDER BY {unsigned integer | column-name} [ORDER BY {unsigned integer | column-name}

[ASC|DESC]] [ASC|DESC]]

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

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

Hands-onHands-on

• LOG on to your database using SQL*PLUS LOG on to your database using SQL*PLUS worksheetworksheet

• Page 107, SQL Coding Exercises and Page 107, SQL Coding Exercises and Questions Questions – Let’s do some of these Let’s do some of these

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

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

CHAPTER 6: CHAPTER 6: JOINSJOINS

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

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

A TYPICAL JOIN OPERATIONA TYPICAL JOIN OPERATION

• The following figure displays the The following figure displays the employee employee and and department department tables. tables.

• The figure illustrates the concept of a JOIN The figure illustrates the concept of a JOIN operation by connecting columns within each table operation by connecting columns within each table with a line.with a line.

• One line connects the One line connects the employeeemployee table's table's emp_dpt_numberemp_dpt_number column with the column with the departmentdepartment table's table's dpt_nodpt_no column. column.

• A second line connects the A second line connects the employeeemployee table's table's emp_ssnemp_ssn column to the column to the departmentdepartment table's table's dep_mgrssndep_mgrssn column. column.

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

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

A TYPICAL JOIN OPERATIONA TYPICAL JOIN OPERATION

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

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

JOINSJOINS

• We will begin our study of JOIN operations by We will begin our study of JOIN operations by focusing on the relationship between the focusing on the relationship between the employeeemployee and and departmentdepartment tables represented by the common tables represented by the common department number values.department number values.

• Our first query lists employee names and Our first query lists employee names and department numbers. This query only retrieves department numbers. This query only retrieves data from the single data from the single employeeemployee table. table.

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

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

JOINSJOINS

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 "Department"emp_dpt_number "Department"FROM employee;FROM employee;Last Name First Name DepartmentLast Name First Name Department------------- -------------- --------------------------- -------------- --------------Bordoloi Bijoy 1Bordoloi Bijoy 1Joyner Suzanne 3Joyner Suzanne 3Zhu Waiman 7Zhu Waiman 7more rows will be displayed . . .more rows will be displayed . . .

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

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

JOINSJOINS

• A large organization can have dozens or even A large organization can have dozens or even hundreds of departments. Thus, the numbers hundreds of departments. Thus, the numbers displayed in the department column shown above displayed in the department column shown above may not be very meaningful. may not be very meaningful.

• Suppose you want the department names instead Suppose you want the department names instead of the department numbers to be listed.of the department numbers to be listed.

• The department names are mentioned in the The department names are mentioned in the “Department” table.“Department” table.

• Hence we need to join the “Employee” and the Hence we need to join the “Employee” and the “Department” tables to get the required results.“Department” tables to get the required results.

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

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

JOINSJOINS

SELECT emp_last_name "Last Name", SELECT emp_last_name "Last Name", emp_first_name "First Name", emp_first_name "First Name", dpt_name "Department Name" dpt_name "Department Name" FROM employee, departmentFROM employee, departmentWHERE employee.emp_dpt_number = department.dpt_no;WHERE employee.emp_dpt_number = department.dpt_no;Last Name First Name Department NameLast Name First Name Department Name------------- ------------- ----------------------------------- ------------- ----------------------Bordoloi Bijoy HeadquartersBordoloi Bijoy HeadquartersJoyner Suzanne Admin and RecordsJoyner Suzanne Admin and RecordsZhu Waiman ProductionZhu Waiman Productionmore rows will be displayed . . .more rows will be displayed . . .

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

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

JOINSJOINS

• The following table shows two tables simply named The following table shows two tables simply named Table_1 and Table_2. Table_1 and Table_2.

• Each table has a single column named Col_1. Each Each table has a single column named Col_1. Each table also has three rows with simple alphabetic table also has three rows with simple alphabetic values stored in the Col_1 column.values stored in the Col_1 column.

Table_1 Table_2 Table_1 Table_2

COL_1COL_1

aa

bb

cc

COL_1COL_1

aa

bb

cc

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

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

JOINSJOINS

SELECT *SELECT *FROM table_1, table_2;FROM table_1, table_2;

COL_1 COL_1COL_1 COL_1-------- ----------------- ---------

aa aab b aac c aaa a bbb b bbc c bba a ccb b cccc cc

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

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

JOINSJOINS• The first row of the “table_1” table was joined with The first row of the “table_1” table was joined with everyevery

row in the “table_2” table.row in the “table_2” table.

• A Cartesian product may not be useful and could be A Cartesian product may not be useful and could be misleading.misleading.

• Always include a WHERE clause in your JOIN statements.Always include a WHERE clause in your JOIN statements.

SELECT *SELECT *

FROM FROM table_1, table_2;table_1, table_2;WHERE table_1.col_1 = table_2.col_1;WHERE table_1.col_1 = table_2.col_1;

col_1 col_1col_1 col_1 -------- -------- -------- --------

a aa a bb b b

cc c c

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

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

JOIN OPERATION RULESJOIN OPERATION RULES

JOINS and the SELECT ClauseJOINS and the SELECT Clause

• A JOIN query always begins with a SELECT A JOIN query always begins with a SELECT clause. clause.

• List the columns to be displayed in the result table List the columns to be displayed in the result table after the SELECT keyword. after the SELECT keyword.

• The result table column order reflects the order in The result table column order reflects the order in which column names are listed in the SELECT which column names are listed in the SELECT clause. clause.

• To modify the order in which column names are To modify the order in which column names are listed, simply rearrange the order of the column listed, simply rearrange the order of the column listing in the SELECT clause. listing in the SELECT clause.

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

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

ExampleExample

SELECT dpt_name "Department Name",SELECT dpt_name "Department Name", emp_last_name "Last Name",emp_last_name "Last Name", emp_first_name "First Name"emp_first_name "First Name"FROM employee e, department dFROM employee e, department dWHERE e.emp_dpt_number = d.dpt_no AND WHERE e.emp_dpt_number = d.dpt_no AND

e.emp_dpt_number = 7;e.emp_dpt_number = 7;

Department Name Last Name First NameDepartment Name Last Name First Name---------------------- -------------- ------------------------------------- -------------- ---------------Production Zhu WaimanProduction Zhu WaimanProduction Bock DouglasProduction Bock DouglasProduction Joshi DineshProduction Joshi DineshProduction Prescott SherriProduction Prescott Sherri

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

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

JOIN OPERATION RULESJOIN OPERATION RULES

• JOIN operations also support the specification of JOIN operations also support the specification of all columns by the use of a simple asterisk (*) in a all columns by the use of a simple asterisk (*) in a SELECT clause. SELECT clause.

• The result table for the query will contain all The result table for the query will contain all columns from both of the tables. columns from both of the tables.

• When the asterisk (*) is used, the column order of When the asterisk (*) is used, the column order of the result table is based on the order in which the result table is based on the order in which tables are listed in the FROM clause.tables are listed in the FROM clause.

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

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

JOINS and the FROM ClauseJOINS and the FROM Clause

• Any SELECT statement that has two or more table names Any SELECT statement that has two or more table names listed in a FROM clause is a JOIN query.listed in a FROM clause is a JOIN query.

• By definition, a JOIN operation retrieves rows from two or By definition, a JOIN operation retrieves rows from two or more tables. more tables.

• The FROM clause is always used to list the tables from The FROM clause is always used to list the tables from which columns are to be retrieved by a JOIN query.which columns are to be retrieved by a JOIN query.

• The FROM clause listing has a limit of 16 table names. The FROM clause listing has a limit of 16 table names. • The order of table name listings is irrelevant to the The order of table name listings is irrelevant to the

production of the result table with one exception – that is, production of the result table with one exception – that is, if you use an asterisk (*) in the SELECT clause, then the if you use an asterisk (*) in the SELECT clause, then the column order in the result table reflects the order in which column order in the result table reflects the order in which tables are listed in the FROM clause. tables are listed in the FROM clause.

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

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

JOINS and the WHERE ClauseJOINS and the WHERE Clause

• The WHERE clause specifies the relationship The WHERE clause specifies the relationship between tables listed in the FROM clause. between tables listed in the FROM clause.

• It also restricts the rows displayed in the result It also restricts the rows displayed in the result table.table.

• The most commonly used JOIN operator is the The most commonly used JOIN operator is the "equal" (=) sign."equal" (=) sign.

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

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

QUALIFYING COLUMN NAMESQUALIFYING COLUMN NAMES

• When column names are ambiguous (the column names When column names are ambiguous (the column names

used are from more than one table) you must qualify them.used are from more than one table) you must qualify them.

SELECT *SELECT *FROM table_1, table_2FROM table_1, table_2WHERE col_1 = col_1;WHERE col_1 = col_1;

• This query is This query is WRONGWRONG. Oracle Server would reject this . Oracle Server would reject this query and generate the error message "ambiguous object.“query and generate the error message "ambiguous object.“

Error at line 3:Error at line 3:

ORA - 00918 : column ambiguously definedORA - 00918 : column ambiguously defined

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

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

QUALIFYING COLUMN NAMESQUALIFYING COLUMN NAMES

• This error message tells you that you have included a This error message tells you that you have included a column name somewhere in the query that exists in more column name somewhere in the query that exists in more than one table listed in the FROM clause.than one table listed in the FROM clause.

• Here the error is in the WHERE clause; however, it is also Here the error is in the WHERE clause; however, it is also possible to make a similar error in the SELECT clause.possible to make a similar error in the SELECT clause.

• The SELECT statement shown below fails to qualify the The SELECT statement shown below fails to qualify the col_1 name in the SELECT clause, and Oracle again col_1 name in the SELECT clause, and Oracle again produces the ORA-00918 error message.produces the ORA-00918 error message.

SELECT col_1SELECT col_1FROM table_1, table_2FROM table_1, table_2WHERE table_1.col_1 = table_2.col_1;WHERE table_1.col_1 = table_2.col_1;ERROR at line 1:ERROR at line 1:ORA-00918: column ambiguously definedORA-00918: column ambiguously defined

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

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

QUALIFYING COLUMN NAMESQUALIFYING COLUMN NAMES

• An ambiguous column name is qualified by using An ambiguous column name is qualified by using the DOT (the DOT (..) connector to connect the table name and ) connector to connect the table name and column name.column name.

• Sometimes it is easier to qualify column names by Sometimes it is easier to qualify column names by using table alias names. using table alias names.

• Often, a single letter is used as an identifier to Often, a single letter is used as an identifier to reduce keystroke requirements. reduce keystroke requirements.

SELECT dpt_name "Department Name", SELECT dpt_name "Department Name", emp_last_name "Last Name",emp_last_name "Last Name", emp_first_name "First Name"emp_first_name "First Name"FROM employee e, department dFROM employee e, department dWHERE e.emp_dpt_number = d.dpt_no AND e.emp_dpt_number = 7;WHERE e.emp_dpt_number = d.dpt_no AND e.emp_dpt_number = 7;

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

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

QUALIFYING COLUMN NAMESQUALIFYING COLUMN NAMES

• The use of the letters "e" and "d" is completely The use of the letters "e" and "d" is completely arbitrary; "t1" and "t2" or any other unique aliases arbitrary; "t1" and "t2" or any other unique aliases could have been used.could have been used.

• The important points to learn are:The important points to learn are:– The alias must follow a table name.The alias must follow a table name.– Use a space to separate a table name and its alias.Use a space to separate a table name and its alias.– The alias must be unique within the SELECT The alias must be unique within the SELECT

statement.statement.• If the column names are not identical you are not If the column names are not identical you are not

required to qualify them, although you still might required to qualify them, although you still might want to for documentation purposeswant to for documentation purposes

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

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

JOIN Operations Using Inequality Operators (<, >)JOIN Operations Using Inequality Operators (<, >)

• You may use any relational operator in a JOIN query. The You may use any relational operator in a JOIN query. The next query uses an inequality operator, the greater than (>) next query uses an inequality operator, the greater than (>) relational operator. relational operator. SELECT emp_first_name "First Name", SELECT emp_first_name "First Name", dep_name "Dependent Name", dep_name "Dependent Name", dep_relationship "Relation"dep_relationship "Relation"FROM employee e, dependent dFROM employee e, dependent dWHERE e.emp_ssn = d.dep_emp_ssn ANDWHERE e.emp_ssn = d.dep_emp_ssn AND e.emp_first_name > d.dep_name;e.emp_first_name > d.dep_name;

First Name Dependent Name RelationFirst Name Dependent Name Relation--------------- --------------------- ------------------------- --------------------- ----------Waiman Jo Ellen DAUGHTERWaiman Jo Ellen DAUGHTERWaiman Andrew SONWaiman Andrew SONWaiman Susan SPOUSEWaiman Susan SPOUSESuzanne Allen SPOUSESuzanne Allen SPOUSEDouglas Deanna DAUGHTERDouglas Deanna DAUGHTER

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

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

Joining More Than Two TablesJoining More Than Two Tables

• While the examples given thus far have joined While the examples given thus far have joined rows from two tables, you can specify up to 16 rows from two tables, you can specify up to 16 tables in a JOIN operation.tables in a JOIN operation.

• The more tables that are included in a JOIN The more tables that are included in a JOIN operation, the longer the query will take to operation, the longer the query will take to process, especially when the tables are large with process, especially when the tables are large with millions of rows per table. millions of rows per table.

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

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

Joining More Than Two TablesJoining More Than Two Tables

• The example shown in the following figure joins three The example shown in the following figure joins three tables to produce a result table based on two different tables to produce a result table based on two different relationships. relationships.

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

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

Joining More Than Two TablesJoining More Than Two Tables

• The SELECT statement to join the tables The SELECT statement to join the tables depicted in the figure is shown here. depicted in the figure is shown here.

SELECT emp_last_name "Last Name", SELECT emp_last_name "Last Name", emp_first_name "First Name", emp_first_name "First Name", 1.10*emp_salary "Raised Salary", p.pro_name "Project"1.10*emp_salary "Raised Salary", p.pro_name "Project"FROM employee e, assignment a, project pFROM employee e, assignment a, project pWHERE e.emp_ssn = a.work_emp_ssn ANDWHERE e.emp_ssn = a.work_emp_ssn AND a.work_pro_number = p.pro_number ANDa.work_pro_number = p.pro_number AND p.pro_name = 'Inventory';p.pro_name = 'Inventory';

Last Name First Name Raised Salary ProjectLast Name First Name Raised Salary Project--------------- --------------- ---------------- -------------------------- --------------- ---------------- -----------Zhu Waiman $47,300 InventoryZhu Waiman $47,300 InventoryMarkis Marcia $27,500 InventoryMarkis Marcia $27,500 InventoryAmin Hyder $27,500 InventoryAmin Hyder $27,500 Inventory

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

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

Joining Tables by Using Two ColumnsJoining Tables by Using Two Columns

• The diagram depicts the relationship at a The diagram depicts the relationship at a university where students enroll in course university where students enroll in course sections. sections.

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

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

Joining Tables by Using Two ColumnsJoining Tables by Using Two Columns

• The SELECT statement that accomplishes the The SELECT statement that accomplishes the JOIN based on two columns is shown below. JOIN based on two columns is shown below.

• This situation arises when the related tables This situation arises when the related tables have have composite primary keycomposite primary key columns. columns.

SELECT s.course_title "Course Title", SELECT s.course_title "Course Title",

e.student_ssn "Student SSN"e.student_ssn "Student SSN"

FROM enrollment e, section sFROM enrollment e, section s

WHERE e.course_number = s.course_number ANDWHERE e.course_number = s.course_number AND

e.section_number = s.section_number;e.section_number = s.section_number;

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

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

OUTER JOIN OperationsOUTER JOIN Operations

• Oracle also supports what is called an outer-Oracle also supports what is called an outer-join. This means that a row will appear in the join. This means that a row will appear in the joined table even though there is no matching joined table even though there is no matching value in the table to be joined. value in the table to be joined.

• Suppose you want to know the names of the Suppose you want to know the names of the employees regardless of whether they have employees regardless of whether they have dependents or not. You can use the outer join as dependents or not. You can use the outer join as follows. follows.

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

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

OUTER JOIN OperationsOUTER JOIN Operations

• The plus sign in parentheses (+) tells Oracle to The plus sign in parentheses (+) tells Oracle to execute an OUTER JOIN operation. execute an OUTER JOIN operation.

• Further, it is the Further, it is the dependentdependent table that is being table that is being outer-joined to the outer-joined to the employeeemployee table because some table because some employees will not have dependents.employees will not have dependents.

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

dep_name "Dependent", dep_name "Dependent", dep_relationship "Relationship"dep_relationship "Relationship"FROM employee e, dependent dFROM employee e, dependent dWHERE e.emp_ssn = d.dep_emp_ssn(+);WHERE e.emp_ssn = d.dep_emp_ssn(+);

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

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

SELECT emp_last_name "Last Name",SELECT emp_last_name "Last Name", emp_first_name "First Name", emp_first_name "First Name", dep_name "Dependent",dep_name "Dependent", dep_relationship "Relationship"dep_relationship "Relationship"FROM employee e, dependent dFROM employee e, dependent dWHERE e.emp_ssn = d.dep_emp_ssn(+);WHERE e.emp_ssn = d.dep_emp_ssn(+);

Last Name First Name Dependent RelationshipLast Name First Name Dependent Relationship--------------- --------------- -------------- --------------------------- --------------- -------------- ------------Bordoloi BijoyBordoloi BijoyJoyner Suzanne Allen SPOUSEJoyner Suzanne Allen SPOUSEZhu Waiman Andrew SONZhu Waiman Andrew SONZhu Waiman Jo Ellen DAUGHTERZhu Waiman Jo Ellen DAUGHTERZhu Waiman Susan SPOUSEZhu Waiman Susan SPOUSEMarkis MarciaMarkis MarciaAmin HyderAmin HyderBock Douglas Deanna DAUGHTERBock Douglas Deanna DAUGHTERBock Douglas Jeffery SONBock Douglas Jeffery SONBock Douglas Mary Ellen SPOUSEBock Douglas Mary Ellen SPOUSEJoshi DineshJoshi DineshPrescott SherriPrescott Sherri12 rows selected.12 rows selected.

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

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

OUTER JOINS and NULL values OUTER JOINS and NULL values

• Management might desire a listing of employees Management might desire a listing of employees with no dependents in order to satisfy some with no dependents in order to satisfy some governmental reporting requirement. governmental reporting requirement.

• We can take advantage of the fact that the We can take advantage of the fact that the dep_namedep_name column will be NULL for employees column will be NULL for employees with no dependents, and simply add a criteria to with no dependents, and simply add a criteria to the WHERE clause to include employees where the WHERE clause to include employees where the the dep_namedep_name column is NULL. column is NULL.

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

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

OUTER JOINS and NULL values OUTER JOINS and NULL values

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

FROM employee e, dependent dFROM employee e, dependent d

WHERE e.emp_ssn = d.dep_emp_ssn(+) ANDWHERE e.emp_ssn = d.dep_emp_ssn(+) AND

d.dep_name IS NULL;d.dep_name IS NULL;

Last Name First NameLast Name First Name

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

Bordoloi BijoyBordoloi Bijoy

Markis MarciaMarkis Marcia

Amin HyderAmin Hyder

Joshi DineshJoshi Dinesh

Prescott SherriPrescott Sherri

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

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

LEFT and RIGHT OUTER JOIN OperationsLEFT and RIGHT OUTER JOIN Operations

• If the If the employeeemployee table is on the left and it is table is on the left and it is outer-joined with the outer-joined with the dependentdependent table table depicted on the right, then this is sometimes depicted on the right, then this is sometimes referred to as a RIGHT OUTER JOIN. referred to as a RIGHT OUTER JOIN.

• Now if you think about it, the entity-Now if you think about it, the entity-relationship diagram could just as easily have relationship diagram could just as easily have been drawn with the been drawn with the dependentdependent table on the table on the left and the left and the employeeemployee table on the right. The table on the right. The same JOIN operation would now be termed a same JOIN operation would now be termed a LEFT OUTER JOIN. LEFT OUTER JOIN.

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

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

LEFT JOINLEFT JOINSELECT emp_last_name "Last Name", emp_first_name "First Name", SELECT emp_last_name "Last Name", emp_first_name "First Name", dep_name "Dependent", dep_relationship "Relationship"dep_name "Dependent", dep_relationship "Relationship"FROM employee e, dependent d FROM employee e, dependent d WHERE WHERE d.dep_emp_ssn(+)d.dep_emp_ssn(+) = e.emp_ssn; = e.emp_ssn;Last Name First Name Dependent RelationshipLast Name First Name Dependent Relationship--------------- --------------- -------------- --------------------------- --------------- -------------- ------------Bordoloi BijoyBordoloi BijoyJoyner Suzanne Allen SPOUSEJoyner Suzanne Allen SPOUSEZhu Waiman Andrew SONZhu Waiman Andrew SONZhu Waiman Jo Ellen DAUGHTERZhu Waiman Jo Ellen DAUGHTERZhu Waiman Susan SPOUSEZhu Waiman Susan SPOUSEMarkis MarciaMarkis MarciaAmin HyderAmin HyderBock Douglas Deanna DAUGHTERBock Douglas Deanna DAUGHTERBock Douglas Jeffery SONBock Douglas Jeffery SONBock Douglas Mary Ellen SPOUSEBock Douglas Mary Ellen SPOUSEJoshi DineshJoshi DineshPrescott SherriPrescott Sherri12 rows selected.12 rows selected.

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

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

SELF-JOIN OperationsSELF-JOIN Operations

• A SELF JOIN operation is used to produce a A SELF JOIN operation is used to produce a result table when the relationship of interest result table when the relationship of interest exists among rows that are stored within a exists among rows that are stored within a single table. single table.

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

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

SELF-JOIN OperationsSELF-JOIN Operations

SELECT e1.emp_last_name || ', ' || e1.emp_first_name "Supervisor",SELECT e1.emp_last_name || ', ' || e1.emp_first_name "Supervisor",

e2.emp_last_name || ', ' || e2.emp_first_name "Employee"e2.emp_last_name || ', ' || e2.emp_first_name "Employee"

FROM employee e1, employee e2FROM employee e1, employee e2

WHERE e1.emp_ssn = e2.emp_superssn;WHERE e1.emp_ssn = e2.emp_superssn;

Supervisor EmployeeSupervisor Employee

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

Bordoloi, Bijoy Joyner, SuzanneBordoloi, Bijoy Joyner, Suzanne

Bordoloi, Bijoy Zhu, WaimanBordoloi, Bijoy Zhu, Waiman

Joyner, Suzanne Markis, MarciaJoyner, Suzanne Markis, Marcia

Joyner, Suzanne Amin, HyderJoyner, Suzanne Amin, Hyder

Zhu, Waiman Bock, DouglasZhu, Waiman Bock, Douglas

Zhu, Waiman Joshi, DineshZhu, Waiman Joshi, Dinesh

Zhu, Waiman Prescott, SherriZhu, Waiman Prescott, Sherri