90
Prentice Hall © 2004 1 COS 346 COS 346 Day 13 Day 13

Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

  • View
    217

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 1

COS 346COS 346

Day 13Day 13

Page 2: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 2

AgendaAgenda• Questions?Questions?• Assignment 5 PostedAssignment 5 Posted

– Due March 20 (right After Break)Due March 20 (right After Break)• Assignment 6 will be posted by March 20Assignment 6 will be posted by March 20• Capstone Project Proposals Due Capstone Project Proposals Due

– ““You must advance your knowledge/skill level beyond that normally expected in You must advance your knowledge/skill level beyond that normally expected in the course.  It is expected that the project will reflect a minimum of 30 hours of the course.  It is expected that the project will reflect a minimum of 30 hours of concentrated effort on your behalf. “concentrated effort on your behalf. “

• If this is for two classes then >60 hours totalIf this is for two classes then >60 hours total– Most picked trivial projects that were rejected. Only two have been accepted so afr.Most picked trivial projects that were rejected. Only two have been accepted so afr.

• More on SQL & SQL ServerMore on SQL & SQL Server– We do chap 5&6 in SQL Text next We do chap 5&6 in SQL Text next – Advanced Queries Advanced Queries

Page 3: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 3

Chapter 5: Aggregate Functions Chapter 5: Aggregate Functions and Grouping of Dataand Grouping of Data

SQL for SQL ServerSQL for SQL ServerBijoy Bordoloi and Douglas BockBijoy Bordoloi and Douglas Bock

Page 4: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 4

OBJECTIVESOBJECTIVES

• Write queries with aggregate functions: SUM, Write queries with aggregate functions: SUM, AVG, COUNT, MAX, and MIN.AVG, COUNT, MAX, and MIN.

• Use the GROUP BY clause to answer complex Use the GROUP BY clause to answer complex managerial questions.managerial questions.

• Use the GROUP BY clause with the WHERE Use the GROUP BY clause with the WHERE and ORDER BY clauses.and ORDER BY clauses.

• Use the HAVING clause to filter out rows from Use the HAVING clause to filter out rows from a result table.a result table.

Page 5: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 5

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 Computer Department? salaries in the Computer Department?

Page 6: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 6

AGGREGATE ROW FUNCTIONS Contd. AGGREGATE ROW FUNCTIONS Contd.

• 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” the highest “MAX” or lowest “MIN” values in a column. values in a column.

Page 7: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 7

AGGREGATE ROW FUNCTIONS Contd.AGGREGATE ROW FUNCTIONS Contd.

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 Aggregate functions can be used in both the SELECT and HAVING clauses (the HAVING SELECT and HAVING clauses (the HAVING clause is covered later in this chapter).clause is covered later in this chapter).

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

Page 8: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 8

EXAMPLEEXAMPLE

• The following query The following query is wrong and will produce an is wrong and will produce an error message.error message.

SELECT *SELECT *FROM employeeFROM employeeWHERE emp_salary > AVG(emp_salary) ;WHERE emp_salary > AVG(emp_salary) ;

An aggregate may not appear in the WHER An aggregate may not appear in the WHER clause unless it is in a subquery contained in a clause unless it is in a subquery contained in a HAVING clause or a select list, and the column HAVING clause or a select list, and the column being aggregated is an outer reference.being aggregated is an outer reference.

  

Page 9: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 9

AGGREGATE ROW FUCTIONSAGGREGATE ROW FUCTIONS

• 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 10: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 10

Agg. Function Example: COUNT(*)Agg. Function Example: COUNT(*)

• If a manager needs to know how many employees If a manager needs to know how many employees work in the organization, COUNT(*) can be used to work in the organization, COUNT(*) can be used to produce this information. produce 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;

----------- ----------- 88

Page 11: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 11

COUNT(* )COUNT(* )

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

• Notice that the result table has no Notice that the result table has no column heading. column heading.

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

Page 12: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 12

COUNT(*) Contd.COUNT(*) Contd.

• 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 13: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 13

COUNT(*) Contd.COUNT(*) Contd.

• 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 14: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 14

COUNT (*) Contd.COUNT (*) Contd.SELECT COUNT(emp_superssn) "Number of Supervised SELECT COUNT(emp_superssn) "Number of Supervised Employees"Employees"FROM employee;FROM employee;

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

77

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

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

88

Page 15: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 15

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 ‘$’+ CONVERT(Char(10), AVG(emp_salary), 1) SELECT ‘$’+ CONVERT(Char(10), AVG(emp_salary), 1) "Average Employee Salary""Average Employee Salary"

FROM employee;FROM employee;

Average Employee Salary Average Employee Salary

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

$ 35,500.00$ 35,500.00

Page 16: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 16

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 ‘$’+ CONVERT(Char(10), AVG(DISTINCT emp_salary), 1) SELECT ‘$’+ CONVERT(Char(10), AVG(DISTINCT emp_salary), 1) "Average Employee Salary""Average Employee Salary"

FROM employee;FROM employee;

Average Employee SalaryAverage Employee Salary

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

$ 38,200.00$ 38,200.00

Page 17: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 17

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 ‘$’+ CONVERT(Char(10), SUM(emp_salary), 1) "Total Salary"SELECT ‘$’+ CONVERT(Char(10), SUM(emp_salary), 1) "Total Salary"

FROM employee;FROM employee;

Total SalaryTotal Salary

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

$ 284,000.00$ 284,000.00

Page 18: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 18

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

136000.0000136000.0000

Page 19: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 19

MIN and MAX FunctionsMIN and MAX Functions

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

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

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

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

FROM employee;FROM employee;

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

Amin ZhuAmin Zhu

Page 20: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 20

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 21: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 21

Using GROUP BY with Aggregate Using GROUP BY with Aggregate Functions Contd.Functions Contd.

When properly used, the GROUP BY clause enables When properly used, the GROUP BY clause enables you to use aggregate functions to answer more you to use aggregate functions to answer more complex managerial questions such as: complex managerial questions such as:

» What is the average salary of employees in each What is the average salary of employees in each department?department?

» How many employees work in each department?How many employees work in each department?» How many employees are working on a particular How many employees are working on a particular

project?project?

Page 22: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 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", COUNT(*) "Employee Count"SELECT emp_dpt_number "Department", COUNT(*) "Employee Count"

FROM employeeFROM employee

GROUP BY emp_dpt_number;GROUP BY emp_dpt_number;

Department Employee CountDepartment Employee Count

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

1 11 1

3 33 3

7 47 4  

Page 23: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 23

GROUP BY ClauseGROUP BY Clause

• SQL Server provides some flexibility in SQL Server provides some flexibility in specifying the GROUP BY clause.specifying the GROUP BY clause.

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

Page 24: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 24

ExampleExample

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

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

Employee CountEmployee Count----------------------------113344  

Page 25: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 25

GROUP BY ClauseGROUP BY Clause

• Note, however, that if your SELECT clause Note, however, that if your SELECT clause includes includes bothboth column names and aggregate column names and aggregate functions, then you functions, then you mustmust also have a GROUP also have a GROUP BY clause in your query. Additionally, the BY clause in your query. Additionally, the column name(s) in the GROUP BY clause column name(s) in the GROUP BY clause must includemust include the column name(s) listed in the the column name(s) listed in the SELECT clause. Otherwise, SQL Server will SELECT clause. Otherwise, SQL Server will return error messages. return error messages.

Page 26: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 26

GROUP BY Clause Contd.GROUP BY Clause Contd.

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

FROM employee; FROM employee;

Server: Msg 8118, Level 16, State 1, Line 2Server: Msg 8118, Level 16, State 1, Line 2

Column 'employee.emp_dpt_number' is invalid in the select Column 'employee.emp_dpt_number' is invalid in the select list because it is not contained in an aggregate list because it is not contained in an aggregate function and there is no GROUP BY clausefunction and there is no GROUP BY clause

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

FROM employeeFROM employee

GROUP BY emp_city;GROUP BY emp_city;

Server: Msg 8120, Level 16, State 1, Line 2Server: Msg 8120, Level 16, State 1, Line 2

Column 'employee.emp_dpt_number' is invalid in the select Column 'employee.emp_dpt_number' is invalid in the select list because it is not contained in an aggregate list because it is not contained in an aggregate function and there is no GROUP BY clause.function and there is no GROUP BY clause.

Page 27: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 27

GROUP BY Clause Contd.GROUP BY Clause Contd.

SELECT SELECT emp_dpt_numberemp_dpt_number "Department", COUNT(*) "Department", COUNT(*) "Employee Count""Employee Count"

FROM employeeFROM employee

GROUP BY GROUP BY emp_dpt_numberemp_dpt_number;;

Department Employee CountDepartment Employee Count

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

1 11 1

3 33 3

7 47 4  

Page 28: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 28

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 CAST(AVG(emp_salary)AS Decimal(10,2)) "Current Average Salary", SELECT CAST(AVG(emp_salary)AS Decimal(10,2)) "Current Average Salary", CAST(AVG(CAST(AVG(emp_salary* 1.25emp_salary* 1.25)AS Decimal(10,2)) "New Average Salary")AS Decimal(10,2)) "New Average Salary"FROM employeeFROM employeeGROUP BY GROUP BY emp_salary * 1.25emp_salary * 1.25;;

Current Average Salary New Average Salary Current Average Salary New Average Salary ---------------------- ------------------ ---------------------- ------------------ 25000.00 31250.0025000.00 31250.0030000.00 37500.0030000.00 37500.0038000.00 47500.0038000.00 47500.0043000.00 53750.0043000.00 53750.0055000.00 68750.0055000.00 68750.00

Page 29: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 29

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

consideration consideration before before any grouping takes place. any grouping takes place.

• The query shown here produces an average hours worked result table The query shown here produces an average hours worked result table for employees with a social security number that is larger than 999-66-for employees with a social security number that is larger than 999-66-0000. 0000.

SELECT work_emp_ssn SSN, AVG(work_hours) "Average Hours Worked"SELECT work_emp_ssn SSN, AVG(work_hours) "Average Hours Worked"

FROM assignment WHERE work_emp_ssn > 999660000FROM assignment WHERE work_emp_ssn > 999660000

GROUP BY work_emp_ssn;GROUP BY work_emp_ssn;

SSN Average Hours Worked SSN Average Hours Worked

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

999666666 NULL999666666 NULL

999887777 20.500000999887777 20.500000

999888888 21.500000999888888 21.500000

Page 30: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 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: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 31

Using GROUP BY With an ORDER BY Clause Using GROUP BY With an ORDER BY Clause Contd.Contd.

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

‘‘$’ + CONVERT(Char(10),AVG(emp_salary), 1) $’ + CONVERT(Char(10),AVG(emp_salary), 1) "Average 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 Salary Department Average Salary

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

3 $ 31,000.003 $ 31,000.00

7 $ 34,000.007 $ 34,000.00

1 $ 55,000.001 $ 55,000.00

Page 32: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 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 in same thing, that is filter rows from inclusion in a result table based on a condition.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: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 33

GROUP BY With a HAVING Clause Contd.GROUP BY With a HAVING Clause Contd.

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

‘‘$’ + CONVERT(Char(10),AVG(emp_salary), 1) $’ + CONVERT(Char(10),AVG(emp_salary), 1) "Average 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 Salary Department Average Salary

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

1 $ 55,000.001 $ 55,000.00

7 $ 34,000.007 $ 34,000.00

Page 34: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 34

GROUP BY With a HAVING Clause Contd.GROUP BY With a HAVING Clause Contd.

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 35: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 35

Combining HAVING Clause with Where clauseCombining HAVING Clause with Where clause

SELECT emp_dpt_number "Department", SELECT emp_dpt_number "Department", ‘‘$’ + CONVERT(Char(10),AVG(emp_salary), $’ + CONVERT(Char(10),AVG(emp_salary),

1) "Average Salary"1) "Average Salary"FROM employeeFROM employeeWHERE emp_dpt_number <> 1WHERE emp_dpt_number <> 1GROUP BY emp_dpt_numberGROUP BY emp_dpt_numberHAVING AVG(emp_salary) > 33000;HAVING AVG(emp_salary) > 33000;

Department Average Salary Department Average Salary ---------- -------------- ---------- -------------- 7 $ 34,000.007 $ 34,000.00

Page 36: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 36

GROUP BY and HAVING ClausesGROUP BY and HAVING Clauses

Standard SQL RulesStandard SQL Rules

The most common use of a HAVING clause is to create result tables The most common use of a HAVING clause is to create result tables containing one row per group, with one or more summary values in containing one row per group, with one or more summary values in the row. To do this your query must meet the following conditions:the row. To do this your query must meet the following conditions:If a SELECT clause includes column names and aggregate functions, If a SELECT clause includes column names and aggregate functions, then columns listed in a SELECT clause must also be listed in the then columns listed in a SELECT clause must also be listed in the GROUP BY expression or they must be arguments of aggregate GROUP BY expression or they must be arguments of aggregate functions. functions.

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

• YOU cannot have a HAVING clause in the absence of the GROUP YOU cannot have a HAVING clause in the absence of the GROUP BY clause.BY clause.

Page 37: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 37

ExampleExample

SELECT SELECT emp_dpt_numberemp_dpt_number "Department", "Department", emp_gender,emp_gender, COUNT(*) "Employee Count"COUNT(*) "Employee Count"

FROM employeeFROM employee

GROUP BY GROUP BY emp_dpt_numberemp_dpt_number

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

Server: Msg 8120, Level 16, State 1, Line 2Server: Msg 8120, Level 16, State 1, Line 2

Column 'employee.emp_gender' is invalid in the Column 'employee.emp_gender' is invalid in the select list because it is not contained in select list because it is not contained in either an aggregate function or the GROUP BY either an aggregate function or the GROUP BY

clause.clause.  

Page 38: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 38

Example Contd.Example Contd.

SELECT SELECT emp_dpt_numberemp_dpt_number "Department", "Department", emp_gender,emp_gender,

COUNT(*) "Employee Count"COUNT(*) "Employee Count"

FROM employeeFROM employee

GROUP BY GROUP BY emp_dpt_number, emp_genderemp_dpt_number, emp_gender

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

Department emp_gender Employee Count Department emp_gender Employee Count

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

3 F 23 F 2

7 M 37 M 3

Page 39: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 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: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 40

HAVING Without a GROUP BY ClauseHAVING Without a GROUP BY Clause

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

FROM employeeFROM employee

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

Server: Msg 8118, Level 16, State 1, Line 2Server: Msg 8118, Level 16, State 1, Line 2

Column 'employee.emp_dpt_number' is invalid Column 'employee.emp_dpt_number' is invalid in the select list because it is not in the select list because it is not contained in an aggregate function and there contained in an aggregate function and there is no GROUP BY clause.is no GROUP BY clause.

Page 41: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 41

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

Examples:Examples:

• The GROUP BY ALL clause displays all groups, even those The GROUP BY ALL clause displays all groups, even those excluded from calculations by a WHERE clause.excluded from calculations by a WHERE 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.

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

Page 42: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 42

SQL extensions to GROUP BY and SQL extensions to GROUP BY and HAVING Clauses Contd.HAVING Clauses Contd.

Example:Example:

SELECT SELECT emp_dpt_numberemp_dpt_number "Department", COUNT(*) "Department", COUNT(*) "Employee Count""Employee Count"

FROM employeeFROM employee

GROUP BY GROUP BY emp_dpt_number, emp_genderemp_dpt_number, emp_gender

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

Department Employee Count Department Employee Count

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

3 23 2

7 37 3

Page 43: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 43

SUMMARYSUMMARYGROUPING AND SUMMARIZING

To Get This Effect: Do This:

Exclude rows before grouping: Use a WHERE clause.

Divide a result table into groups: Use a GROUP BY clause.

Calculate summary values for each group:

Include one or more aggregates in the SELECT clause listing.

Exclude groups from the result table:

Use a HAVING clause.

If This Happens: Look For This:

All qualified rows in all qualified groups display:

The SELECT clause listing contains a column name that is not in the GROUP BY clause.

All excluded groups display Query includes GROUP BY ALL

Page 44: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 44

Chapter 6: JoinsChapter 6: Joins

SQL for SQL ServerSQL for SQL ServerBijoy Bordoloi and Douglas BockBijoy Bordoloi and Douglas Bock

Page 45: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 45

OBJECTIVESOBJECTIVES

• Learn the basic join operation rules.Learn the basic join operation rules.• Write equijoin and inequality join queries by using Write equijoin and inequality join queries by using

the WHERE clause.the WHERE clause.• Write equijoin and inequality join queries by using Write equijoin and inequality join queries by using

the JOIN keyword in the FROM clause.the JOIN keyword in the FROM clause.• Write complex join queries with more than two Write complex join queries with more than two

tables and more than two columns.tables and more than two columns.• Write outer join queries.Write outer join queries.• Write self join (recursive) queries.Write self join (recursive) queries.

Page 46: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 46

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 47: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 47

A TYPICAL JOIN OPERATIONA TYPICAL JOIN OPERATION

Page 48: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 48

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 49: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 49

JOINS Contd.JOINS Contd.

SELECT CAST(emp_last_name As CHAR(12)) "Last Name", SELECT CAST(emp_last_name As CHAR(12)) "Last Name", CAST(emp_first_name As CHAR(12)) "First Name", CAST(emp_first_name As CHAR(12)) "First Name", CAST(emp_dpt_number As CHAR(4)) "Dept"CAST(emp_dpt_number As CHAR(4)) "Dept"FROM employee;FROM employee;

Last Name First Name Dept Last Name First Name Dept ------------ ------------ ---- ------------ ------------ ---- Bock Douglas 7 Bock Douglas 7 Amin Hyder 3 Amin Hyder 3 Joshi Dinesh 7 Joshi Dinesh 7 Zhu Waiman 7 Zhu Waiman 7 more rows will be displayed . . .more rows will be displayed . . .

Page 50: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 50

JOINS Contd.JOINS Contd.

• 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 Suppose you want the department namesdepartment names instead 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 51: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 51

JOINS Contd.JOINS Contd.

• Joins can be specified in either the FROM or Joins can be specified in either the FROM or WHERE clauses. WHERE clauses.

• The join conditions combine with the search The join conditions combine with the search conditions in the WHERE and HAVING clauses conditions in the WHERE and HAVING clauses to control the rows that are selected from the to control the rows that are selected from the tables referenced in the FROM clause. tables referenced in the FROM clause.

• Early standards for SQL specified the use of a Early standards for SQL specified the use of a WHERE clause to join tables. The newer WHERE clause to join tables. The newer ANSI/ISO SQL-99 standard uses the FROM ANSI/ISO SQL-99 standard uses the FROM clause to carry out a JOIN operation. clause to carry out a JOIN operation.

• The older syntax is, however, still valid, and is The older syntax is, however, still valid, and is expected to remain valid in the future (except for expected to remain valid in the future (except for OUTER JOIN).OUTER JOIN).

Page 52: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 52

JOINS Contd.JOINS Contd.

/* JOIN using the WHERE clause *//* JOIN using the WHERE clause */SELECT CAST(emp_last_name As CHAR(12)) "Last Name", SELECT CAST(emp_last_name As CHAR(12)) "Last Name", CAST(emp_first_name As CHAR(12)) "First Name", CAST(emp_first_name As CHAR(12)) "First Name", dpt_name "Department Name"dpt_name "Department Name"FROM employee, departmentFROM employee, departmentWHERE emp_dpt_number = dpt_no;WHERE emp_dpt_number = dpt_no;

/* JOIN using the FROM clause *//* JOIN using the FROM clause */SELECT CAST(emp_last_name As CHAR(12)) "Last Name", SELECT CAST(emp_last_name As CHAR(12)) "Last Name", CAST(emp_first_name As CHAR(12)) "First Name", CAST(emp_first_name As CHAR(12)) "First Name", dpt_name "Department Name"dpt_name "Department Name"FROM employee e JOIN department d ON (e.emp_dpt_number = FROM employee e JOIN department d ON (e.emp_dpt_number =

d.dpt_no)d.dpt_no);;

• Output is identical for both the queries.Output is identical for both the queries.

Page 53: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 53

JOINS Contd.JOINS Contd.

Last Name First Name Department Name Last Name First Name Department Name

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

Bock Douglas ProductionBock Douglas Production

Amin Hyder Admin and RecordsAmin Hyder Admin and Records

Joshi Dinesh ProductionJoshi Dinesh Production

Zhu Waiman ProductionZhu Waiman Production

more rows will be displayed . . .more rows will be displayed . . .

Page 54: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 54

HOW JOINS ARE PROCESSEDHOW JOINS ARE PROCESSED

• Conceptually, when two tables are joined, SQL Conceptually, when two tables are joined, SQL creates a creates a CartesianCartesian product of the tables. product of the tables.

• A Cartesian product consists of all possible A Cartesian product consists of all possible combinations of the rows from each of the combinations of the rows from each of the tables regardless of whether or not the rows are tables regardless of whether or not the rows are related to one another. related to one another.

• Therefore, when a table with 10 rows is joined Therefore, when a table with 10 rows is joined with a table with 20 rows, the Cartesian product with a table with 20 rows, the Cartesian product is 200 rows (10 x 20 = 200 ). is 200 rows (10 x 20 = 200 ).

Page 55: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 55

HOW JOINS ARE PROCESSED HOW JOINS ARE PROCESSED Contd.Contd.

• Following are two tables simply named Table_1 and Following are two tables simply named Table_1 and Table_2. 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 56: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 56

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 57: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 57

JOINS Contd.JOINS Contd.• 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 58: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 58

JOIN ExampleJOIN Example• Using the WHERE clauseUsing the WHERE clause

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

Last Name First Name Department Name Last Name First Name Department Name ------------ ------------ -------------------- ------------ ------------ -------------------- Bock Douglas ProductionBock Douglas ProductionJoshi Dinesh ProductionJoshi Dinesh ProductionZhu Waiman ProductionZhu Waiman ProductionPrescott Sherri ProductionPrescott Sherri Production

Page 59: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 59

JOIN Example Contd.JOIN Example Contd.

• Using the FROM clauseUsing the FROM clause

SELECT CAST(emp_last_name As CHAR(12)) "Last SELECT CAST(emp_last_name As CHAR(12)) "Last Name", Name",

CAST(emp_first_name As CHAR(12)) "First Name", CAST(emp_first_name As CHAR(12)) "First Name",

dpt_name "Department Name"dpt_name "Department Name"

FROM employee e JOIN department d ON FROM employee e JOIN department d ON (e.emp_dpt_number = d.dpt_no)(e.emp_dpt_number = d.dpt_no)

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

Page 60: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 60

JOIN Example Contd.JOIN Example Contd.

• Using a combination of FROM and Using a combination of FROM and WHERE clauses (recommended method)WHERE clauses (recommended method)

SELECT CAST(emp_last_name As CHAR(12)) "Last SELECT CAST(emp_last_name As CHAR(12)) "Last Name", Name",

CAST(emp_first_name As CHAR(12)) "First Name", CAST(emp_first_name As CHAR(12)) "First Name",

dpt_name "Department Name"dpt_name "Department Name"

FROM employee e JOIN department d ON FROM employee e JOIN department d ON (e.emp_dpt_number = d.dpt_no)(e.emp_dpt_number = d.dpt_no)

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

Page 61: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 61

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 62: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 62

ExampleExample

SELECT dpt_name "Department Name",SELECT dpt_name "Department Name",

CAST(emp_last_name As CHAR(12)) "Last Name", CAST(emp_last_name As CHAR(12)) "Last Name",

CAST(emp_first_name As CHAR(12)) "First Name" CAST(emp_first_name As CHAR(12)) "First Name"

FROM employee e JOIN department d ON (e.emp_dpt_number = FROM employee e JOIN department d ON (e.emp_dpt_number = d.dpt_no)d.dpt_no)

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

Department NameDepartment Name Last Name First Name Last Name First Name

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

Production Bock Douglas Production Bock Douglas

Production Joshi Dinesh Production Joshi Dinesh

Production Zhu Waiman Production Zhu Waiman

Production Prescott Sherri Production Prescott Sherri

Page 63: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 63

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 the tables. columns from both 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 64: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 64

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 256 table names. The FROM clause listing has a limit of 256 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 the one exception – that production of the result table with the one exception – that is, if you use an asterisk (*) in the SELECT clause, then is, if you use an asterisk (*) in the SELECT clause, then the column order in the result table reflects the order in the column order in the result table reflects the order in which tables are listed in the FROM clause. which tables are listed in the FROM clause.

Page 65: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 65

JOINS and the FROM Clause Contd.JOINS and the FROM Clause Contd.• As explained earlier, you can specify the join conditions in As explained earlier, you can specify the join conditions in

a FROM clause by explicitly using the JOIN clause within a FROM clause by explicitly using the JOIN clause within the FROM clause. the FROM clause.

• You can also specify the You can also specify the typetype of JOIN such as INNER, of JOIN such as INNER, LEFT OUTER, RIGHT OUTER or FULL OUTER. LEFT OUTER, RIGHT OUTER or FULL OUTER.

• If you do not specify the If you do not specify the typetype of join then, by default, the of join then, by default, the join operation is always an INNER join. join operation is always an INNER join.

• We did not indicate the We did not indicate the typetype of join in any of the example of join in any of the example queries thus far. So, they are all examples of INNER join queries thus far. So, they are all examples of INNER join operations. operations.

• The various OUTER join operations are covered later in The various OUTER join operations are covered later in this chapter.this chapter.

Page 66: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 66

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.

• TThe order of selection criteria or JOIN he order of selection criteria or JOIN operations is not important. operations is not important.

Page 67: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 67

JOINS and the WHERE Clause JOINS and the WHERE Clause Contd.Contd.

SELECT CAST(emp_last_name As CHAR(12)) "Last Name", SELECT CAST(emp_last_name As CHAR(12)) "Last Name",

CAST(emp_first_name As CHAR(12)) "First Name", CAST(emp_first_name As CHAR(12)) "First Name",

dpt_name "Department Name"dpt_name "Department Name"

FROM employee e, department dFROM employee e, department d

WHERE e.emp_dpt_number = 7WHERE e.emp_dpt_number = 7

AND e.emp_dpt_number = d.dpt_no;AND e.emp_dpt_number = d.dpt_no;

Last Name First Name Department Name Last Name First Name Department Name

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

Bock Douglas ProductionBock Douglas Production

Joshi Dinesh ProductionJoshi Dinesh Production

Zhu Waiman ProductionZhu Waiman Production

Prescott Sherri ProductionPrescott Sherri Production

Page 68: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 68

JOINS and the WHERE Clause JOINS and the WHERE Clause Contd.Contd.

A note of caution though! A note of caution though! The scenario exemplified in the The scenario exemplified in the previous example applies only if you are joining tables using the previous example applies only if you are joining tables using the WHERE clause. If you elect to both join tables and specify row WHERE clause. If you elect to both join tables and specify row selection criteria in a FROM clause, then you MUST specify the JOIN selection criteria in a FROM clause, then you MUST specify the JOIN operation operation beforebefore specifying the row selection criteria. Otherwise, SQL specifying the row selection criteria. Otherwise, SQL Server will generate an error message. Server will generate an error message.

SELECT CAST(emp_last_name As CHAR(12)) "Last Name", SELECT CAST(emp_last_name As CHAR(12)) "Last Name",

CAST(emp_first_name As CHAR(12)) "First Name", CAST(emp_first_name As CHAR(12)) "First Name",

dpt_name "Department Name"dpt_name "Department Name"

FROM emp_dpt_number = 7FROM emp_dpt_number = 7 and and

employee e JOIN department d ON (e.emp_dpt_number = d.dpt_no);employee e JOIN department d ON (e.emp_dpt_number = d.dpt_no);

Server: Msg 170, Level 15, State 1, Line 5Server: Msg 170, Level 15, State 1, Line 5

Line 5: Incorrect syntax near '='.Line 5: Incorrect syntax near '='.

Page 69: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 69

QUALIFYING COLUMN NAMESQUALIFYING COLUMN NAMES• Normally you do not need to create alias names for tables.Normally you do not need to create alias names for tables.

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 themused 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, SQL Server would reject this , SQL Server would reject this query and generate an error message.query and generate an error message.

Server: Msg 209, Level 16, State 1, Line 2Server: Msg 209, Level 16, State 1, Line 2Ambiguous column name 'Col_1'.Ambiguous column name 'Col_1'.

Page 70: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 70

QUALIFYING COLUMN NAMES Contd.QUALIFYING COLUMN NAMES Contd.

• 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 SQL Server again col_1 name in the SELECT clause, and SQL Server again produces an error message.produces an error message.

SELECT SELECT col_1col_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;

Server: Msg 209, Level 16, State 1, Line 2Server: Msg 209, Level 16, State 1, Line 2Ambiguous column name 'Col_1'.Ambiguous column name 'Col_1'.

Page 71: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 71

QUALIFYING COLUMN NAMES Contd.QUALIFYING COLUMN NAMES Contd.

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

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

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

SELECT CAST(SELECT CAST(ee.emp_last_name As CHAR(12)) "Last Name", .emp_last_name As CHAR(12)) "Last Name", CAST(CAST(ee.emp_first_name As CHAR(12)) "First Name", .emp_first_name As CHAR(12)) "First Name", dpt_name "Department Name"dpt_name "Department Name"

FROM employee e FROM employee e JOIN JOIN department d department d ON ON ((ee.emp_dpt_number = .emp_dpt_number = dd.dpt_no).dpt_no)

WHERE WHERE ee.emp_dpt_number = 7;.emp_dpt_number = 7;

Page 72: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 72

QUALIFYING COLUMN NAMES Contd.QUALIFYING COLUMN NAMES Contd.

• 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 purposes.want to for documentation purposes.

Page 73: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 73

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

• The most commonly used JOIN operator is the "equal" (=) sign. The most commonly used JOIN operator is the "equal" (=) sign. • You may use any relational operator in a JOIN query. The next query You may use any relational operator in a JOIN query. The next query

uses an inequality operator, the greater than (>) relational operator. uses an inequality operator, the greater than (>) relational operator.

SELECT CAST(emp_last_name As CHAR(12)) "Emp Last Name", SELECT CAST(emp_last_name As CHAR(12)) "Emp Last Name", CAST(dep_name AS CHAR(12)) "Dependent Name"CAST(dep_name AS CHAR(12)) "Dependent Name"FROM employee e JOIN dependent d ON (e.emp_ssn <> d.dep_emp_ssn)FROM employee e JOIN dependent d ON (e.emp_ssn <> d.dep_emp_ssn)WHERE e.emp_last_name IN ('Bordoloi', 'Bock')WHERE e.emp_last_name IN ('Bordoloi', 'Bock')ORDER BY emp_last_name;ORDER BY emp_last_name;Emp Last Name Dependent Name Emp Last Name Dependent Name ------------- -------------- ------------- -------------- Bock Jo Ellen Bock Jo Ellen . .. . . .. .

Bock Rita Bock Rita Bordoloi Deanna Bordoloi Deanna More rows are displayed..More rows are displayed..

Page 74: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 74

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 256 rows from two tables, you can specify up to 256 tables in a JOIN operation for SQL Server.tables in a JOIN operation for SQL Server.

• 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 75: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 75

Joining More Than Two Tables Joining More Than Two Tables Contd.Contd.

• The example shown in following figure joins three The example shown in 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 76: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 76

Joining More Than Two Tables Joining More Than Two Tables Contd.Contd.

• ExampleExample

SELECT CASTSELECT CAST(emp_last_name (emp_last_name As CHAR(12)) "Last Name", As CHAR(12)) "Last Name", CAST(CAST(emp_first_nameemp_first_name As CHAR(12)) "First Name", As CHAR(12)) "First Name", ''$'$' + + CONVERT (CHAR (12), 1.10*emp_salary, 1) "Raised Salary", CONVERT (CHAR (12), 1.10*emp_salary, 1) "Raised Salary", p.pro_name p.pro_name "Project""Project"FROM employee e JOIN assignment a ON (e.emp_ssn = a.work_emp_ssn) FROM employee e JOIN assignment a ON (e.emp_ssn = a.work_emp_ssn) JOIN project p ON (a.work_pro_number = p.pro_number)JOIN project p ON (a.work_pro_number = p.pro_number)WHERE p.pro_name = 'Inventory';WHERE p.pro_name = 'Inventory';

Last Name First Name Raised Salary Project Last Name First Name Raised Salary Project

------------ ------------ ------------- --------- ------------ ------------ ------------- --------- Amin Hyder $27500.000000 InventoryAmin Hyder $27500.000000 InventoryZhu Waiman $47300.000000 InventoryZhu Waiman $47300.000000 InventoryMarkis Marcia $27500.000000 InventoryMarkis Marcia $27500.000000 Inventory

Page 77: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 77

Joining More Than Two Tables Joining More Than Two Tables Contd.Contd.

• Note that in the previous example you are Note that in the previous example you are displaying data only from two tables, displaying data only from two tables, employee employee and and projectproject. Yet, you are joining three tables, . Yet, you are joining three tables, employee, assignmentemployee, assignment, and , and projectproject!!

• This is because the tables, This is because the tables, employee employee and and project,project, are not are not directlydirectly joinable as they do not have any joinable as they do not have any directdirect relationship represented by ‘primary- relationship represented by ‘primary-foreign key’ relationships. foreign key’ relationships.

Page 78: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 78

Joining More Than Two Tables Joining More Than Two Tables Contd.Contd.

• A typical join condition specifies a foreign key A typical join condition specifies a foreign key from one table and its associated primary key in from one table and its associated primary key in the other table. In order to display data from the other table. In order to display data from tables linked through an association table, you tables linked through an association table, you may need to join three or four or even more may need to join three or four or even more tables. tables.

• However, you can join only two tables at a time. However, you can join only two tables at a time. That is, you can have only two table names in That is, you can have only two table names in each join condition. Thus, if you are joining each join condition. Thus, if you are joining twotwo tables then you must have at least tables then you must have at least oneone join join condition; if you are joining condition; if you are joining nn tables then you tables then you must have at least must have at least n-1n-1 join conditions! join conditions!

Page 79: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 79

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 80: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 80

Joining Tables by Using Two Columns Joining Tables by Using Two Columns Contd.Contd.

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

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

SELECT s.course_title "Course Title", e.student_ssn "Student SSN"SELECT s.course_title "Course Title", e.student_ssn "Student SSN"FROM enrollment e, section sFROM enrollment e, section sWHERE 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;

/* Join conditions in the FROM clause *//* Join conditions in the FROM clause */SELECT s.course_title "Course Title", e.student_ssn "Student SSN"SELECT s.course_title "Course Title", e.student_ssn "Student SSN"FROM enrollment e JOIN section s FROM enrollment e JOIN section s ON (e.course_number = s.course_number) ANDON (e.course_number = s.course_number) AND (e.section_number = s.section_number);(e.section_number = s.section_number);

Page 81: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 81

OUTER JOIN OperationsOUTER JOIN Operations

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

• There are three types of outer joins: LEFT, There are three types of outer joins: LEFT, RIGHT, and FULL. They all begin with an RIGHT, and FULL. They all begin with an INNER JOIN, and then they add back some of INNER JOIN, and then they add back some of the rows that have been dropped.the rows that have been dropped.

Page 82: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 82

OUTER JOIN OPERATIONS:Types of OUTER JOIN OPERATIONS:Types of OUTER JOIN Contd.OUTER JOIN Contd.

• A LEFT OUTER JOIN adds back all the rows A LEFT OUTER JOIN adds back all the rows that are dropped from the first (left) table in the that are dropped from the first (left) table in the join condition, and output columns from the join condition, and output columns from the second (right) table are set to NULL. second (right) table are set to NULL.

• A RIGHT OUTER JOIN adds back all the rows A RIGHT OUTER JOIN adds back all the rows that are dropped from the second (right) table in that are dropped from the second (right) table in the join condition, and output columns from the the join condition, and output columns from the first (left) table are set to NULL. first (left) table are set to NULL.

• The FULL OUTER JOIN adds back all the The FULL OUTER JOIN adds back all the rows that are dropped from both the tables.rows that are dropped from both the tables.

Page 83: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 83

OUTER JOIN Operations CONTD.OUTER JOIN Operations CONTD.

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

SELECT CAST(emp_last_name As CHAR(12)) "Last SELECT CAST(emp_last_name As CHAR(12)) "Last Name", Name",

CAST(emp_first_name As CHAR(12)) "First Name", CAST(emp_first_name As CHAR(12)) "First Name", CAST(dep_name As CHAR(12)) "Dependent", CAST(dep_name As CHAR(12)) "Dependent", CAST(dep_relationship As CHAR(8)) "Relationship"CAST(dep_relationship As CHAR(8)) "Relationship"FROM FROM employeeemployee LEFT OUTER JOIN LEFT OUTER JOIN dependentdependent ON ON

(emp_ssn = dep_emp_ssn);(emp_ssn = dep_emp_ssn);

Page 84: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 84

OUTER JOIN Operations Contd.OUTER JOIN Operations Contd.Last Name First Name Dependent Relationship Last Name First Name Dependent Relationship ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ Bock Douglas Deanna DAUGHTERBock Douglas Deanna DAUGHTERBock Douglas Jeffery SON Bock Douglas Jeffery SON Bock Douglas Mary Ellen SPOUSE Bock Douglas Mary Ellen SPOUSE Bock Douglas Michelle DAUGHTERBock Douglas Michelle DAUGHTERBock Douglas Rachael DAUGHTERBock Douglas Rachael DAUGHTERAmin Hyder NULL NULLAmin Hyder NULL NULLJoshi Dinesh NULL NULLJoshi Dinesh NULL NULLZhu Waiman Andrew SON Zhu Waiman Andrew SON Zhu Waiman Jo Ellen DAUGHTERZhu Waiman Jo Ellen DAUGHTERZhu Waiman Susan SPOUSE Zhu Waiman Susan SPOUSE Joyner Suzanne Allen SPOUSE Joyner Suzanne Allen SPOUSE Bordoloi Bijoy Anita DAUGHTERBordoloi Bijoy Anita DAUGHTERBordoloi Bijoy Mita SPOUSE Bordoloi Bijoy Mita SPOUSE Bordoloi Bijoy Monica DAUGHTERBordoloi Bijoy Monica DAUGHTERBordoloi Bijoy Rita DAUGHTERBordoloi Bijoy Rita DAUGHTERMarkis Marcia NULL NULLMarkis Marcia NULL NULLPrescott Sherri NULL NULLPrescott Sherri NULL NULL(17 row(s) affected)(17 row(s) affected)

Page 85: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 85

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 to satisfy some with no dependents 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 86: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 86

OUTER JOINS and NULL values Contd. OUTER JOINS and NULL values Contd.

SELECT CAST(emp_last_name As CHAR(12)) "Last Name", SELECT CAST(emp_last_name As CHAR(12)) "Last Name",

CAST(emp_first_name As CHAR(12)) "First Name", CAST(emp_first_name As CHAR(12)) "First Name",

CAST(dep_name As CHAR(12)) "Dependent", CAST(dep_name As CHAR(12)) "Dependent",

CAST(dep_relationship As CHAR(8)) "Relationship"CAST(dep_relationship As CHAR(8)) "Relationship"

FROM employee LEFT OUTER JOIN dependent ON (emp_ssn = FROM employee LEFT OUTER JOIN dependent ON (emp_ssn = dep_emp_ssn)dep_emp_ssn)

WHERE dep_name IS NULL;WHERE dep_name IS NULL;

Last Name First Name Dependent Relationship Last Name First Name Dependent Relationship

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

Amin Hyder NULL NULLAmin Hyder NULL NULL

Joshi Dinesh NULL NULLJoshi Dinesh NULL NULL

Markis Marcia NULL NULLMarkis Marcia NULL NULL

Prescott Sherri NULL NULLPrescott Sherri NULL NULL

Page 87: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 87

RIGHT OUTER JOINRIGHT OUTER JOINSELECT CAST(emp_last_name As CHAR(12)) "Last Name", SELECT CAST(emp_last_name As CHAR(12)) "Last Name", CAST(emp_first_name As CHAR(12)) "First Name", CAST(emp_first_name As CHAR(12)) "First Name", CAST(dep_name As CHAR(12)) "Dependent", CAST(dep_name As CHAR(12)) "Dependent", CAST(dep_relationship As CHAR(8)) "Relationship"CAST(dep_relationship As CHAR(8)) "Relationship"FROM FROM dependentdependent RIGHT OUTER JOIN RIGHT OUTER JOIN employeeemployee ON (emp_ssn = dep_emp_ssn);ON (emp_ssn = dep_emp_ssn);

Last Name First Name Dependent Relationship Last Name First Name Dependent Relationship ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ Bock Douglas Deanna DAUGHTERBock Douglas Deanna DAUGHTERBock Douglas Jeffery SON Bock Douglas Jeffery SON Bock Douglas Mary Ellen SPOUSE Bock Douglas Mary Ellen SPOUSE Bock Douglas Michelle DAUGHTERBock Douglas Michelle DAUGHTERBock Douglas Rachael DAUGHTERBock Douglas Rachael DAUGHTERAmin Hyder NULL NULLAmin Hyder NULL NULLJoshi Dinesh NULL NULLJoshi Dinesh NULL NULLZhu Waiman Andrew SON Zhu Waiman Andrew SON Zhu Waiman Jo Ellen DAUGHTERZhu Waiman Jo Ellen DAUGHTERZhu Waiman Susan SPOUSE Zhu Waiman Susan SPOUSE Joyner Suzanne Allen SPOUSE Joyner Suzanne Allen SPOUSE Bordoloi Bijoy Anita DAUGHTERBordoloi Bijoy Anita DAUGHTERBordoloi Bijoy Mita SPOUSE Bordoloi Bijoy Mita SPOUSE Bordoloi Bijoy Monica DAUGHTERBordoloi Bijoy Monica DAUGHTERBordoloi Bijoy Rita DAUGHTERBordoloi Bijoy Rita DAUGHTERMarkis Marcia NULL NULLMarkis Marcia NULL NULLPrescott Sherri NULL NULLPrescott Sherri NULL NULL(17 row(s) affected)(17 row(s) affected)

Page 88: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 88

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 89: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 89

SELF-JOIN Operations Contd.SELF-JOIN Operations Contd.SELECT CAST(e1.emp_last_name + ', ' + e1.emp_first_name As SELECT CAST(e1.emp_last_name + ', ' + e1.emp_first_name As

CHAR(20)) "Supervisor",CHAR(20)) "Supervisor",

CAST(e2.emp_last_name + ', ' + e2.emp_first_name As CHAR(20)) CAST(e2.emp_last_name + ', ' + e2.emp_first_name As CHAR(20))

"Employee""Employee"

FROM employee e1 JOIN employee e2 ON (e1.emp_ssn = FROM employee e1 JOIN employee e2 ON (e1.emp_ssn = e2.emp_superssn)e2.emp_superssn)

ORDER BY e2.emp_superssn;ORDER BY e2.emp_superssn;

Supervisor Employee Supervisor Employee

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

Zhu, Waiman Bock, Douglas Zhu, Waiman Bock, Douglas

Zhu, Waiman Joshi, Dinesh Zhu, Waiman Joshi, Dinesh

Zhu, Waiman Prescott, Sherri Zhu, Waiman Prescott, Sherri

Joyner, Suzanne Markis, Marcia Joyner, Suzanne Markis, Marcia

Joyner, Suzanne Amin, Hyder Joyner, Suzanne Amin, Hyder

Bordoloi, Bijoy Zhu, Waiman Bordoloi, Bijoy Zhu, Waiman

Bordoloi, Bijoy Joyner, SuzanneBordoloi, Bijoy Joyner, Suzanne

Page 90: Prentice Hall © 20041 COS 346 Day 13. Prentice Hall © 20042 Agenda Questions?Questions? Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After

Prentice Hall © 2004 90

SUMMARYSUMMARY

• The JOIN operation enables you to combine The JOIN operation enables you to combine data from several tables. data from several tables.

• You can specify your join conditions either You can specify your join conditions either in the FROM clause (newer syntax) or in in the FROM clause (newer syntax) or in the WHERE clause (older syntax).the WHERE clause (older syntax).

• You typically join tables using You typically join tables using inner joininner join based on equality of columns (based on equality of columns (equijoinequijoin). ).

• However, you also learned about some However, you also learned about some other type of joins such as other type of joins such as outer joinouter join and and self joinself join (recursive). (recursive).