Presentation is loading. Please wait.

Presentation is loading. Please wait.

Prentice Hall © 20041 COS 346 Day 14. 7-2 Agenda Questions?Questions? Assignment 5 CorrectedAssignment 5 Corrected –1 A, 1 B, 4 C’s, 1 F and 1 MIA Assignment.

Similar presentations


Presentation on theme: "Prentice Hall © 20041 COS 346 Day 14. 7-2 Agenda Questions?Questions? Assignment 5 CorrectedAssignment 5 Corrected –1 A, 1 B, 4 C’s, 1 F and 1 MIA Assignment."— Presentation transcript:

1 Prentice Hall © 20041 COS 346 Day 14

2 7-2 Agenda Questions?Questions? Assignment 5 CorrectedAssignment 5 Corrected –1 A, 1 B, 4 C’s, 1 F and 1 MIA Assignment 6 DueAssignment 6 Due Assignment 7 PostedAssignment 7 Posted –Due March 30 New Time lineNew Time line More on SQL & SQL ServerMore on SQL & SQL Server –Chap 6 & 7 –Joins & Subqueries

3 New time line MarchMarch –23 - SQL 6 & 7 Assignment 6 dueAssignment 6 due –26 - SQL 8 & 9 –30 - SQL 10 Assignment 7 dueAssignment 7 due Progress reportProgress report AprilApril –2 Database Redesign –6 - Database redesign Quiz 2Quiz 2 Assignment 8 dueAssignment 8 due –9 - Managing Multiuser databases –13 - Managing Multiuser databases Assignment 9 due –16 Managing Multiuser databases –20 Database access standards Progress report –23 - Database access standards Assignment 10 due –27 Quiz 3 Capstones Presentations Due

4 Prentice Hall © 20044 Chapter 6: Joins SQL for SQL Server Bijoy Bordoloi and Douglas Bock

5 Prentice Hall © 20045 OBJECTIVES Learn the basic join operation rules.Learn the basic join operation rules. Write equijoin and inequality join queries by using the WHERE clause.Write equijoin and inequality join queries by using the WHERE clause. Write equijoin and inequality join queries by using the JOIN keyword in the FROM clause.Write equijoin and inequality join queries by using the JOIN keyword in the FROM clause. Write complex join queries with more than two tables and more than two columns.Write complex join queries with more than two tables and more than two columns. Write outer join queries.Write outer join queries. Write self join (recursive) queries.Write self join (recursive) queries.

6 Prentice Hall © 20046 A TYPICAL JOIN OPERATION The following figure displays the employee and department tables.The following figure displays the employee and department tables. The figure illustrates the concept of a JOIN operation by connecting columns within each table with a line.The figure illustrates the concept of a JOIN operation by connecting columns within each table with a line. One line connects the employee table’s emp_dpt_number column with the department table's dpt_no column.One line connects the employee table’s emp_dpt_number column with the department table's dpt_no column. A second line connects the employee table’s emp_ssn column to the department table’s dep_mgrssn column.A second line connects the employee table’s emp_ssn column to the department table’s dep_mgrssn column.

7 Prentice Hall © 20047 A TYPICAL JOIN OPERATION

8 Prentice Hall © 20048 JOINS We will begin our study of JOIN operations by focusing on the relationship between the employee and department tables represented by the common department number values.We will begin our study of JOIN operations by focusing on the relationship between the employee and department tables represented by the common department number values. Our first query lists employee names and department numbers. This query only retrieves data from the single employee table.Our first query lists employee names and department numbers. This query only retrieves data from the single employee table.

9 Prentice Hall © 20049 JOINS Contd. 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; Last Name First Name Dept ------------ ------------ ---- Bock Douglas 7 Amin Hyder 3 Joshi Dinesh 7 Zhu Waiman 7 more rows will be displayed...

10 Prentice Hall © 200410 JOINS Contd. A large organization can have dozens or even hundreds of departments. Thus, the numbers displayed in the department column shown above may not be very meaningful.A large organization can have dozens or even hundreds of departments. Thus, the numbers displayed in the department column shown above may not be very meaningful. Suppose you want the department names instead of the department numbers to be listed.Suppose you want the department names instead of the department numbers to be listed. The department names are mentioned in the “Department” table.The department names are mentioned in the “Department” table. Hence we need to join the “Employee” and the “Department” tables to get the required results.Hence we need to join the “Employee” and the “Department” tables to get the required results.

11 Prentice Hall © 200411 JOINS Contd. Joins can be specified in either the FROM or WHERE clauses.Joins can be specified in either the FROM or WHERE clauses. The join conditions combine with the search conditions in the WHERE and HAVING clauses to control the rows that are selected from the tables referenced in the FROM clause.The join conditions combine with the search conditions in the WHERE and HAVING clauses to control the rows that are selected from the tables referenced in the FROM clause. Early standards for SQL specified the use of a WHERE clause to join tables. The newer ANSI/ISO SQL-99 standard uses the FROM clause to carry out a JOIN operation.Early standards for SQL specified the use of a WHERE clause to join tables. The newer ANSI/ISO SQL-99 standard uses the FROM clause to carry out a JOIN operation. The older syntax is, however, still valid, and is expected to remain valid in the future (except for OUTER JOIN).The older syntax is, however, still valid, and is expected to remain valid in the future (except for OUTER JOIN).

12 Prentice Hall © 200412 JOINS Contd. /* JOIN using the WHERE clause */ 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, department WHERE emp_dpt_number = dpt_no; /* JOIN using the FROM clause */ 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 = d.dpt_no); Output is identical for both the queries.Output is identical for both the queries.

13 Prentice Hall © 200413 JOINS Contd. Last Name First Name Department Name ------------ ------------ --------------- Bock Douglas Production Amin Hyder Admin and Records Joshi Dinesh Production Zhu Waiman Production more rows will be displayed...

14 Prentice Hall © 200414 HOW JOINS ARE PROCESSED Conceptually, when two tables are joined, SQL creates a Cartesian product of the tables.Conceptually, when two tables are joined, SQL creates a Cartesian product of the tables. A Cartesian product consists of all possible combinations of the rows from each of the tables regardless of whether or not the rows are related to one another.A Cartesian product consists of all possible combinations of the rows from each of the tables regardless of whether or not the rows are related to one another. Therefore, when a table with 10 rows is joined with a table with 20 rows, the Cartesian product is 200 rows (10 x 20 = 200 ).Therefore, when a table with 10 rows is joined with a table with 20 rows, the Cartesian product is 200 rows (10 x 20 = 200 ).

15 Prentice Hall © 200415 HOW JOINS ARE PROCESSED Contd. Following are two tables simply named Table_1 and Table_2.Following are two tables simply named Table_1 and Table_2. Each table has a single column named Col_1. Each table also has three rows with simple alphabetic values stored in the Col_1 column.Each table has a single column named Col_1. Each table also has three rows with simple alphabetic values stored in the Col_1 column. Table_1 Table_2 Table_1 Table_2 COL_1 COL_1 a b c a b c

16 Prentice Hall © 200416JOINS SELECT * FROM table_1, table_2; COL_1 COL_1 -------- --------- a a b a c a a b b b c b a c b c cc

17 Prentice Hall © 200417 JOINS Contd. The first row of the “table_1” table was joined with every row in the “table_2” table.The first row of the “table_1” table was joined with every row in the “table_2” table. A Cartesian product may not be useful and could be misleading.A Cartesian product may not be useful and could be misleading. Always include a WHERE clause in your JOIN statements.Always include a WHERE clause in your JOIN statements. SELECT * FROM table_1, table_2; WHERE table_1.col_1 = table_2.col_1; col_1 col_1 col_1 col_1 -------- -------- -------- -------- a a a a b b b b c c c c

18 Prentice Hall © 200418 JOIN Example Using the WHERE clauseUsing the WHERE clause 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 d 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 ------------ ------------ -------------------- Bock Douglas Production Joshi Dinesh Production Zhu Waiman Production Prescott Sherri Production

19 Prentice Hall © 200419 JOIN Example Contd. Using the FROM clauseUsing the FROM clause 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 = d.dpt_no) AND e.emp_dpt_number = 7; AND e.emp_dpt_number = 7;

20 Prentice Hall © 200420 JOIN Example Contd. Using a combination of FROM and WHERE clauses (recommended method)Using a combination of FROM and WHERE clauses (recommended method) 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 = d.dpt_no) WHERE e.emp_dpt_number = 7;

21 Prentice Hall © 200421 JOIN OPERATION RULES JOINS and the SELECT Clause A JOIN query always begins with a SELECT clause.A JOIN query always begins with a SELECT clause. List the columns to be displayed in the result table after the SELECT keyword.List the columns to be displayed in the result table after the SELECT keyword. The result table column order reflects the order in which column names are listed in the SELECT clause.The result table column order reflects the order in which column names are listed in the SELECT clause. To modify the order in which column names are listed, simply rearrange the order of the column listing in the SELECT clause.To modify the order in which column names are listed, simply rearrange the order of the column listing in the SELECT clause.

22 Prentice Hall © 200422Example 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 = d.dpt_no) WHERE e.emp_dpt_number = 7; Department Name Last Name First Name -------------------- ------------ ------------ Production Bock Douglas Production Joshi Dinesh Production Zhu Waiman Production Prescott Sherri

23 Prentice Hall © 200423 JOIN OPERATION RULES JOIN operations also support the specification of all columns by the use of a simple asterisk (*) in a SELECT clause.JOIN operations also support the specification of all columns by the use of a simple asterisk (*) in a SELECT clause. The result table for the query will contain all columns from both the tables.The result table for the query will contain all columns from both the tables. When the asterisk (*) is used, the column order of the result table is based on the order in which tables are listed in the FROM clause.When the asterisk (*) is used, the column order of the result table is based on the order in which tables are listed in the FROM clause.

24 Prentice Hall © 200424 JOINS and the FROM Clause Any SELECT statement that has two or more table names listed in a FROM clause is a JOIN query.Any SELECT statement that has two or more table names listed in a FROM clause is a JOIN query. By definition, a JOIN operation retrieves rows from two or more tables.By definition, a JOIN operation retrieves rows from two or more tables. The FROM clause is always used to list the tables from which columns are to be retrieved by a JOIN query.The FROM clause is always used to list the tables from 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 production of the result table with the one exception – that is, if you use an asterisk (*) in the SELECT clause, then the column order in the result table reflects the order in which tables are listed in the FROM clause.The order of table name listings is irrelevant to the production of the result table with the one exception – that is, if you use an asterisk (*) in the SELECT clause, then the column order in the result table reflects the order in which tables are listed in the FROM clause.

25 Prentice Hall © 200425 JOINS and the FROM Clause Contd. As explained earlier, you can specify the join conditions in a FROM clause by explicitly using the JOIN clause within the FROM clause.As explained earlier, you can specify the join conditions in a FROM clause by explicitly using the JOIN clause within the FROM clause. You can also specify the type of JOIN such as INNER, LEFT OUTER, RIGHT OUTER or FULL OUTER.You can also specify the type of JOIN such as INNER, LEFT OUTER, RIGHT OUTER or FULL OUTER. If you do not specify the type of join then, by default, the join operation is always an INNER join.If you do not specify the type of join then, by default, the join operation is always an INNER join. We did not indicate the type of join in any of the example queries thus far. So, they are all examples of INNER join operations.We did not indicate the type of join in any of the example queries thus far. So, they are all examples of INNER join operations. The various OUTER join operations are covered later in this chapter.The various OUTER join operations are covered later in this chapter.

26 Prentice Hall © 200426 JOINS and the WHERE Clause The WHERE clause specifies the relationship between tables listed in the FROM clause.The WHERE clause specifies the relationship between tables listed in the FROM clause. It also restricts the rows displayed in the result table.It also restricts the rows displayed in the result table. T he order of selection criteria or JOIN operations is not important.T he order of selection criteria or JOIN operations is not important.

27 Prentice Hall © 200427 JOINS and the WHERE Clause Contd. 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 d WHERE e.emp_dpt_number = 7 AND e.emp_dpt_number = d.dpt_no; Last Name First Name Department Name ------------ ------------ -------------------- Bock Douglas Production Joshi Dinesh Production Zhu Waiman Production Prescott Sherri Production

28 Prentice Hall © 200428 JOINS and the WHERE Clause Contd. A note of caution though! The scenario exemplified in the previous example applies only if you are joining tables using the WHERE clause. If you elect to both join tables and specify row selection criteria in a FROM clause, then you MUST specify the JOIN operation before specifying the row selection criteria. Otherwise, SQL Server will generate an error message. 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 = 7 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 5 Line 5: Incorrect syntax near '='.

29 Prentice Hall © 200429 QUALIFYING COLUMN NAMES Normally you do not need to create alias names for tables. When column names are ambiguous (the column names used are from more than one table) you must qualify themNormally you do not need to create alias names for tables. When column names are ambiguous (the column names used are from more than one table) you must qualify them SELECT * FROM table_1, table_2 WHERE col_1 = col_1; This query is WRONG, SQL Server would reject this query and generate an error message.This query is WRONG, SQL Server would reject this query and generate an error message. Server: Msg 209, Level 16, State 1, Line 2 Ambiguous column name 'Col_1'.

30 Prentice Hall © 200430 QUALIFYING COLUMN NAMES Contd. This error message tells you that you have included a column name somewhere in the query that exists in more than one table listed in the FROM clause.This error message tells you that you have included a column name somewhere in the query that exists in more than one table listed in the FROM clause. Here the error is in the WHERE clause; however, it is also possible to make a similar error in the SELECT clause.Here the error is in the WHERE clause; however, it is also possible to make a similar error in the SELECT clause. The SELECT statement shown below fails to qualify the col_1 name in the SELECT clause, and SQL Server again produces an error message.The SELECT statement shown below fails to qualify the col_1 name in the SELECT clause, and SQL Server again produces an error message. SELECT col_1 FROM table_1, table_2 WHERE table_1.col_1 = table_2.col_1; Server: Msg 209, Level 16, State 1, Line 2 Ambiguous column name 'Col_1'.

31 Prentice Hall © 200431 QUALIFYING COLUMN NAMES Contd. An ambiguous column name is qualified by using the DOT (.) connector to connect the table name and column name.An ambiguous column name is qualified by using the DOT (.) connector to connect the table name and column name. Sometimes it is easier to qualify column names by using table alias names.Sometimes it is easier to qualify column names by using table alias names. Often, a single letter is used as an identifier to reduce keystroke requirements.Often, a single letter is used as an identifier to reduce keystroke requirements. SELECT CAST(e.emp_last_name As CHAR(12)) "Last Name", CAST(e.emp_first_name As CHAR(12)) "First Name", CAST(e.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 = d.dpt_no) WHERE e.emp_dpt_number = 7;

32 Prentice Hall © 200432 QUALIFYING COLUMN NAMES Contd. The use of the letters “e” and “d” is completely arbitrary; “t1” and “t2” or any other unique aliases could have been used.The use of the letters “e” and “d” is completely arbitrary; “t1” and “t2” or any other unique aliases could have been used. The important points to learn are:The important points to learn are: –The alias must follow a table name. –Use a space to separate a table name and its alias. –The alias must be unique within the SELECT statement. If the column names are not identical you are not required to qualify them, although you still might want to for documentation purposes.If the column names are not identical you are not required to qualify them, although you still might want to for documentation purposes.

33 Prentice Hall © 200433 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 uses an inequality operator, the greater than (>) relational operator.You may use any relational operator in a JOIN query. The next query uses an inequality operator, the greater than (>) relational operator. 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) WHERE e.emp_last_name IN ('Bordoloi', 'Bock') ORDER BY emp_last_name; Emp Last Name Dependent Name ------------- -------------- Bock Jo Ellen.... Bock Rita Bordoloi Deanna More rows are displayed..

34 Prentice Hall © 200434 Joining More Than Two Tables While the examples given thus far have joined rows from two tables, you can specify up to 256 tables in a JOIN operation for SQL Server.While the examples given thus far have joined rows from two tables, you can specify up to 256 tables in a JOIN operation for SQL Server. The more tables that are included in a JOIN operation, the longer the query will take to process, especially when the tables are large with millions of rows per table.The more tables that are included in a JOIN operation, the longer the query will take to process, especially when the tables are large with millions of rows per table.

35 Prentice Hall © 200435 Joining More Than Two Tables Contd. The example shown in following figure joins three tables to produce a result table based on two different relationships.The example shown in following figure joins three tables to produce a result table based on two different relationships.

36 Prentice Hall © 200436 Joining More Than Two Tables Contd. ExampleExample 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", '$' + CONVERT (CHAR (12), 1.10*emp_salary, 1) "Raised Salary", '$' + CONVERT (CHAR (12), 1.10*emp_salary, 1) "Raised Salary", p.pro_name "Project" p.pro_name "Project" 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'; Last Name First Name Raised Salary Project ------------ ------------ ------------- --------- Amin Hyder $27500.000000 Inventory Zhu Waiman $47300.000000 Inventory Markis Marcia $27500.000000 Inventory

37 Prentice Hall © 200437 Joining More Than Two Tables Contd. Note that in the previous example you are displaying data only from two tables, employee and project. Yet, you are joining three tables, employee, assignment, and project!Note that in the previous example you are displaying data only from two tables, employee and project. Yet, you are joining three tables, employee, assignment, and project! This is because the tables, employee and project, are not directly joinable as they do not have any direct relationship represented by ‘primary- foreign key’ relationships.This is because the tables, employee and project, are not directly joinable as they do not have any direct relationship represented by ‘primary- foreign key’ relationships.

38 Prentice Hall © 200438 Joining More Than Two Tables Contd. A typical join condition specifies a foreign key from one table and its associated primary key in the other table. In order to display data from tables linked through an association table, you may need to join three or four or even more tables.A typical join condition specifies a foreign key from one table and its associated primary key in the other table. In order to display data from tables linked through an association table, you may need to join three or four or even more tables. However, you can join only two tables at a time. That is, you can have only two table names in each join condition. Thus, if you are joining two tables then you must have at least one join condition; if you are joining n tables then you must have at least n-1 join conditions!However, you can join only two tables at a time. That is, you can have only two table names in each join condition. Thus, if you are joining two tables then you must have at least one join condition; if you are joining n tables then you must have at least n-1 join conditions!

39 Prentice Hall © 200439 Joining Tables by Using Two Columns The diagram depicts the relationship at a university where students enroll in course sections.The diagram depicts the relationship at a university where students enroll in course sections.

40 Prentice Hall © 200440 Joining Tables by Using Two Columns Contd. The SELECT statement that accomplishes the JOIN based on two columns is shown below.The SELECT statement that accomplishes the JOIN based on two columns is shown below. This situation arises when the related tables have composite primary key columns.This situation arises when the related tables have composite primary key columns. SELECT s.course_title "Course Title", e.student_ssn "Student SSN" FROM enrollment e, section s WHERE 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 */ SELECT s.course_title "Course Title", e.student_ssn "Student SSN" FROM enrollment e JOIN section s ON (e.course_number = s.course_number) AND ON (e.course_number = s.course_number) AND (e.section_number = s.section_number); (e.section_number = s.section_number);

41 Prentice Hall © 200441 OUTER JOIN Operations SQL Server also supports what is called an outer-join. This means that a row will appear in the joined table even though there is no matching value in the table to be joined.SQL Server also supports what is called an outer-join. This means that a row will appear in the joined table even though there is no matching value in the table to be joined. There are three types of outer joins: LEFT, RIGHT, and FULL. They all begin with an INNER JOIN, and then they add back some of the rows that have been dropped.There are three types of outer joins: LEFT, RIGHT, and FULL. They all begin with an INNER JOIN, and then they add back some of the rows that have been dropped.

42 Prentice Hall © 200442 OUTER JOIN OPERATIONS:Types of OUTER JOIN Contd. A LEFT OUTER JOIN adds back all the rows that are dropped from the first (left) table in the join condition, and output columns from the second (right) table are set to NULL.A LEFT OUTER JOIN adds back all the rows that are dropped from the first (left) table in the join condition, and output columns from the second (right) table are set to NULL. A RIGHT OUTER JOIN adds back all the rows that are dropped from the second (right) table in the join condition, and output columns from the first (left) table are set to NULL.A RIGHT OUTER JOIN adds back all the rows that are dropped from the second (right) table in the join condition, and output columns from the first (left) table are set to NULL. The FULL OUTER JOIN adds back all the rows that are dropped from both the tables.The FULL OUTER JOIN adds back all the rows that are dropped from both the tables.

43 Prentice Hall © 200443 OUTER JOIN Operations CONTD. Suppose you want to know the names of the employees regardless of whether they have dependents or not. You can use the OUTER JOIN as follows:Suppose you want to know the names of the employees regardless of whether they have dependents or not. You can use the OUTER JOIN as follows: 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 = dep_emp_ssn);

44 Prentice Hall © 200444 OUTER JOIN Operations Contd. Last Name First Name Dependent Relationship ------------ ------------ ------------ ------------ Bock Douglas Deanna DAUGHTER Bock Douglas Jeffery SON Bock Douglas Mary Ellen SPOUSE Bock Douglas Michelle DAUGHTER Bock Douglas Rachael DAUGHTER Amin Hyder NULL NULL Joshi Dinesh NULL NULL Zhu Waiman Andrew SON Zhu Waiman Jo Ellen DAUGHTER Zhu Waiman Susan SPOUSE Joyner Suzanne Allen SPOUSE Bordoloi Bijoy Anita DAUGHTER Bordoloi Bijoy Mita SPOUSE Bordoloi Bijoy Monica DAUGHTER Bordoloi Bijoy Rita DAUGHTER Markis Marcia NULL NULL Prescott Sherri NULL NULL (17 row(s) affected)

45 Prentice Hall © 200445 OUTER JOINS and NULL values Management might desire a listing of employees with no dependents to satisfy some governmental reporting requirement.Management might desire a listing of employees with no dependents to satisfy some governmental reporting requirement. We can take advantage of the fact that the dep_name column will be NULL for employees with no dependents, and simply add a criteria to the WHERE clause to include employees where the dep_name column is NULL.We can take advantage of the fact that the dep_name column will be NULL for employees with no dependents, and simply add a criteria to the WHERE clause to include employees where the dep_name column is NULL.

46 Prentice Hall © 200446 OUTER JOINS and NULL values Contd. 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 = dep_emp_ssn) WHERE dep_name IS NULL; Last Name First Name Dependent Relationship ------------ ------------ ------------ ------------ Amin Hyder NULL NULL Joshi Dinesh NULL NULL Markis Marcia NULL NULL Prescott Sherri NULL NULL

47 Prentice Hall © 200447 RIGHT OUTER JOIN 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 dependent RIGHT OUTER JOIN employee ON (emp_ssn = dep_emp_ssn); Last Name First Name Dependent Relationship ------------ ------------ ------------ ------------ Bock Douglas Deanna DAUGHTER Bock Douglas Jeffery SON Bock Douglas Mary Ellen SPOUSE Bock Douglas Michelle DAUGHTER Bock Douglas Rachael DAUGHTER Amin Hyder NULL NULL Joshi Dinesh NULL NULL Zhu Waiman Andrew SON Zhu Waiman Jo Ellen DAUGHTER Zhu Waiman Susan SPOUSE Joyner Suzanne Allen SPOUSE Bordoloi Bijoy Anita DAUGHTER Bordoloi Bijoy Mita SPOUSE Bordoloi Bijoy Monica DAUGHTER Bordoloi Bijoy Rita DAUGHTER Markis Marcia NULL NULL Prescott Sherri NULL NULL (17 row(s) affected)

48 Prentice Hall © 200448 SELF-JOIN Operations A SELF JOIN operation is used to produce a result table when the relationship of interest exists among rows that are stored within a single table.A SELF JOIN operation is used to produce a result table when the relationship of interest exists among rows that are stored within a single table.

49 Prentice Hall © 200449 SELF-JOIN Operations Contd. SELECT CAST(e1.emp_last_name + ', ' + e1.emp_first_name As 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 = e2.emp_superssn) ORDER BY e2.emp_superssn; Supervisor Employee -------------------- -------------------- Zhu, Waiman Bock, Douglas Zhu, Waiman Joshi, Dinesh Zhu, Waiman Prescott, Sherri Joyner, Suzanne Markis, Marcia Joyner, Suzanne Amin, Hyder Bordoloi, Bijoy Zhu, Waiman Bordoloi, Bijoy Joyner, Suzanne

50 Prentice Hall © 200450 SUMMARY The JOIN operation enables you to combine data from several tables.The JOIN operation enables you to combine data from several tables. You can specify your join conditions either in the FROM clause (newer syntax) or in the WHERE clause (older syntax).You can specify your join conditions either in the FROM clause (newer syntax) or in the WHERE clause (older syntax). You typically join tables using inner join based on equality of columns (equijoin).You typically join tables using inner join based on equality of columns (equijoin). However, you also learned about some other type of joins such as outer join and self join (recursive).However, you also learned about some other type of joins such as outer join and self join (recursive).

51 Bordoloi and Bock Chapter 7: Subqueries SQL for SQL Server Bijoy Bordoloi and Douglas Bock

52 Bordoloi and Bock Objectives Learn the formal subquery definition and write a subquery.Learn the formal subquery definition and write a subquery. Learn the subquery restrictions.Learn the subquery restrictions. Use the IN operator when writing a subquery.Use the IN operator when writing a subquery. Nest subqueries at multiple levels.Nest subqueries at multiple levels. Use comparison operators.Use comparison operators. Use the ALL and ANY keywords.Use the ALL and ANY keywords. Write correlated subqueries including the EXISTS operator.Write correlated subqueries including the EXISTS operator. Use the ORDER BY clause in queries with a subquery.Use the ORDER BY clause in queries with a subquery.

53 Bordoloi and Bock Example Query /* SQL Example 7.1 */ SELECT CAST(emp_last_name As CHAR(12)) "Last Name", CAST(emp_first_name As CHAR(12)) "First Name", emp_dpt_number "Dept", '$' + CONVERT (CHAR (10), emp_salary, 1) "Salary" FROM employee WHERE emp_salary 25000 AND emp_dpt_number IN (3, 7); Last Name First Name Dept Salary ––––-------- ––––-------- ––---- –––—-------- Bock Douglas 7 $ 30,000.00 Amin Hyder 3 $ 25,000.00 Joshi Dinesh 7 $ 38,000.00 more rows are displayed... Here the emp_salary and emp_dpt_number are known in advance.

54 Bordoloi and Bock Breaking a Query into Subtasks Management needs a list of employee names who earn a salary equal to the minimum salary paid to any employee, and the minimum salary will certainly change over time. Step 1: Identify the minimum salary.Management needs a list of employee names who earn a salary equal to the minimum salary paid to any employee, and the minimum salary will certainly change over time. Step 1: Identify the minimum salary. /* SQL Example 7.2 */ SELECT MIN(emp_salary) "Min Salary" FROM employee; Min Salary -------------- 25000.0000

55 Bordoloi and Bock Task 2: Writing the Subquery Add the query as a subquery in the WHERE clause.Add the query as a subquery in the WHERE clause. /* SQL Example 7.3 */ SELECT CAST(emp_last_name As CHAR(12)) "Last Name", CAST(emp_first_name As CHAR(12)) "First Name", '$' + CONVERT(CHAR(10), emp_salary, 1) "Salary" FROM employee WHERE emp_salary = (SELECT MIN(emp_salary) FROM employee); Last Name First Name Salary ––––-------- ––––-------- –––—-------- Amin Hyder $ 25,000.00 Markis Marcia $ 25,000.00 Prescott Sherri $ 25,000.00

56 Bordoloi and Bock SUBQUERY Formal Definition: The use of a SELECT statement inside one of the clauses of another SELECT statement, e.g., a subquery is a query within a query.Formal Definition: The use of a SELECT statement inside one of the clauses of another SELECT statement, e.g., a subquery is a query within a query. Subqueries enable you to write queries that select data rows for criteria that are actually developed while the query is executing at run time.Subqueries enable you to write queries that select data rows for criteria that are actually developed while the query is executing at run time. The criteria values for a WHERE clause are unknown at design time.The criteria values for a WHERE clause are unknown at design time.

57 Bordoloi and Bock SUBQUERY TYPES There are three basic types of subqueries. We will study each of these in the remainder of this chapter.There are three basic types of subqueries. We will study each of these in the remainder of this chapter. Type 1: Subqueries that operate on lists by use of the IN operator or with a comparison operator modified by the ANY or ALL optional keywords. These subqueries can return a group of values, but the values must be from a single column of a table. In other words, the SELECT clause of the subquery must contain only one expression or column name.

58 Bordoloi and Bock SUBQUERY TYPES Type 2: Subqueries that use an unmodified comparison operator (=,, <>) – these subqueries must return only a single, scalar value. Type 3: Subqueries that use the EXISTS operator to test the existence of data rows satisfying specified criteria.

59 Bordoloi and Bock SUBQUERY – General Rules A subquery SELECT statement is very similar to the SELECT statement used to begin a regular or outer query. The complete syntax of a subquery is shown below.A subquery SELECT statement is very similar to the SELECT statement used to begin a regular or outer query. The complete syntax of a subquery is shown below. (SELECT [DISTINCT] subquery_select_parameter FROM {table_name | view_name} {table_name | view_name}... [WHERE search_conditions] [GROUP BY column_name [,column_name ]...] [HAVING search_conditions] )

60 Bordoloi and Bock Clause Restrictions The SELECT clause of a subquery must contain only one expression, only one aggregate function, or only one column name.The SELECT clause of a subquery must contain only one expression, only one aggregate function, or only one column name. The value(s) returned by a subquery must be join compatible with the WHERE clause of the outer query.The value(s) returned by a subquery must be join compatible with the WHERE clause of the outer query.

61 Bordoloi and Bock Example of Join Compatibility The dep_emp_ssn and emp_ssn columns share a common domain of possible values. /* SQL Example 7.4 */ SELECT CAST(emp_last_name As CHAR(12)) "Last Name", CAST(emp_first_name As CHAR(12)) "First Name" FROM employee WHERE emp_ssn IN (SELECT dep_emp_ssn FROM dependent); Last Name First Name ––––----- ––-------- Bock Douglas Zhu Waiman Joyner Suzanne Bordoloi Bijoy

62 Bordoloi and Bock Data-Type Join Compatibility In addition to concerns about the domain of values returned from a subquery, the data type of the returned column value(s) must be join compatible.In addition to concerns about the domain of values returned from a subquery, the data type of the returned column value(s) must be join compatible. Join-compatible data types are data types that SQL Server will convert automatically when matching data in criteria conditions.Join-compatible data types are data types that SQL Server will convert automatically when matching data in criteria conditions. Example: It would make no sense to compare the emp_ssn column to the dep_date_of_birth column.Example: It would make no sense to compare the emp_ssn column to the dep_date_of_birth column.

63 Bordoloi and Bock Data-Type Join Compatibility Contd. SQL Server maps ANSI standard data types to T-SQL data types.SQL Server maps ANSI standard data types to T-SQL data types. Conversion is automatic among any of these ANSI numeric data types when making numeric comparisons:Conversion is automatic among any of these ANSI numeric data types when making numeric comparisons: –int (integer) –smallint (small integer) –decimal –float

64 Bordoloi and Bock Data-Type Join Compatibility Contd. SQL Server does not make comparisons based on column names.SQL Server does not make comparisons based on column names. Columns from two tables that are being compared may have different names as long as they have a shared domain and the same data type or convertible data types.Columns from two tables that are being compared may have different names as long as they have a shared domain and the same data type or convertible data types.

65 Bordoloi and Bock Other Restrictions There are additional restrictions for subqueries. The DISTINCT keyword cannot be used in subqueries that include a GROUP BY clause.The DISTINCT keyword cannot be used in subqueries that include a GROUP BY clause. Subqueries cannot manipulate their results internally. This means that a subquery cannot include the ORDER BY clause (unless a TOP keyword is in the SELECT clause), the COMPUTE clause, or the INTO keyword.Subqueries cannot manipulate their results internally. This means that a subquery cannot include the ORDER BY clause (unless a TOP keyword is in the SELECT clause), the COMPUTE clause, or the INTO keyword. A result table can only include columns from a table named in the outer query’s FROM clause.A result table can only include columns from a table named in the outer query’s FROM clause.

66 Bordoloi and Bock SUBQUERIES AND THE IN Operator Here, a subquery produces a list of values for the subquery result table.Here, a subquery produces a list of values for the subquery result table. Subqueries that are introduced with the keyword IN take the general form:Subqueries that are introduced with the keyword IN take the general form: –WHERE expression [NOT] IN (subquery) The only difference in the use of the IN operator with subqueries is that the list does not consist of hard-coded values.The only difference in the use of the IN operator with subqueries is that the list does not consist of hard-coded values.

67 Bordoloi and Bock IN Operator Example /* SQL Example 7.6 */ SELECT CAST(emp_last_name As CHAR(12)) "Last Name", CAST(emp_first_name As CHAR(12)) "First Name" FROM employee WHERE emp_ssn IN (SELECT dep_emp_ssn FROM dependent WHERE dep_gender 'M'); Last Name First Name ––––-------- ––––--------- Bock Douglas Zhu Waiman Joyner Suzanne

68 Bordoloi and Bock Understanding the IN Operator with Subqueries Conceptually, this SELECT statement is evaluated in two steps. First, the inner query returns the identification numbers of those employees that have male dependents.Conceptually, this SELECT statement is evaluated in two steps. First, the inner query returns the identification numbers of those employees that have male dependents. /* SQL Example 7.7 */ SELECT dep_emp_ssn FROM dependent WHERE dep_gender 'M'; dep_emp_ssn –––—------- 999111111 999444444 999555555

69 Bordoloi and Bock Understanding the IN Operator with Subqueries Cont. Next, the list of social security number values is substituted into the outer query as the object of the IN operator. Conceptually, the outer query now looks like the following.Next, the list of social security number values is substituted into the outer query as the object of the IN operator. Conceptually, the outer query now looks like the following. /* SQL Example 7.8 */ SELECT CAST(emp_last_name As CHAR(12)) "Last Name", CAST(emp_first_name As CHAR(12)) "First Name" FROM employee WHERE emp_ssn IN (999444444, 999555555, 999111111); Last Name First Name ––––-------- –---------––– Bock Douglas Zhu Waiman Joyner Suzanne

70 Bordoloi and Bock Comparing a Subquery to a Join Query The previous subquery can also be written as a join query.The previous subquery can also be written as a join query. /* SQL Example 7.9 */ SELECT CAST(emp_last_name As CHAR(12)) "Last Name", CAST(emp_first_name As CHAR(12)) "First Name" FROM employee e JOIN dependent d ON (e.emp_ssn = d.dep_emp_ssn) WHERE d.dep_gender = 'M'; Last Name First Name ––––-------- ––––--------- Bock Douglas Zhu Waiman Joyner Suzanne

71 Bordoloi and Bock When to Use a Subquery vs. a Join Query Use a subquery when the result table displays columns from a single table. Use a join query when the result displays columns from two or more tables. Use a sub-query when the existence of values must be checked with the EXISTS operator—a sub-query may perform better than a join. The EXISTS operator is discussed later in the chapter.

72 Bordoloi and Bock The NOT IN Operator Like the IN operator, the NOT IN operator can take the result of a subquery as the operator object.Like the IN operator, the NOT IN operator can take the result of a subquery as the operator object. /* SQL Example 7.10 */ SELECT CAST(emp_last_name As CHAR(12)) "Last Name", CAST(emp_first_name As CHAR(12)) "First Name" FROM employee WHERE emp_ssn NOT IN (SELECT dep_emp_ssn FROM dependent); Last Name First Name ––––-------- –--------–––- Amin Hyder Joshi Dinesh Markis Marcia Prescott Sherri

73 Bordoloi and Bock The NOT IN Operator Contd. The inner query in SQL Example 7.10 produces an intermediate result table containing the social security numbers of employees who have dependents in the dependent table.The inner query in SQL Example 7.10 produces an intermediate result table containing the social security numbers of employees who have dependents in the dependent table. Conceptually, the outer query compares each row of the employee table against the result table. If the employee social security number is NOT found in the result table produced by the inner query, then it is included in the final result table.Conceptually, the outer query compares each row of the employee table against the result table. If the employee social security number is NOT found in the result table produced by the inner query, then it is included in the final result table.

74 Bordoloi and Bock MULTIPLE LEVELS OF NESTING Subqueries may themselves contain subqueries.Subqueries may themselves contain subqueries. When the WHERE clause of a subquery has as its object another subquery, these are termed nested subqueries.When the WHERE clause of a subquery has as its object another subquery, these are termed nested subqueries. SQL Server has no practical limit on the number of queries that can be nested in a WHERE clause.SQL Server has no practical limit on the number of queries that can be nested in a WHERE clause. Consider the problem of producing a listing of employees that worked more than 10 hours on the project named Order Entry.Consider the problem of producing a listing of employees that worked more than 10 hours on the project named Order Entry.

75 Bordoloi and Bock Nested Subquery Example /* SQL Example 7.11 */ SELECT CAST(emp_last_name As CHAR(12)) "Last Name", CAST(emp_first_name As CHAR(12)) "First Name" FROM employee WHERE emp_ssn IN (SELECT work_emp_ssn FROM assignment WHERE work_hours > 10 AND work_pro_number IN (SELECT pro_number FROM project WHERE pro_name = 'Order Entry') ); Last Name First Name ––––-------- ---------–––– Bock Douglas Prescott Sherri

76 Bordoloi and Bock Understanding Nested Subqueries In order to understand this subquery’s execution, begin your examination with the lowest subquery.In order to understand this subquery’s execution, begin your examination with the lowest subquery. Executing it independently of the outer queries produces the following scalar result table.Executing it independently of the outer queries produces the following scalar result table. /* SQL Example 7.12 */ SELECT pro_number FROM project WHERE pro_name = 'Order Entry'; pro_number –––------- 1

77 Bordoloi and Bock Understanding Nested Subqueries Contd. Substitute the project number into the IN operator list for the intermediate subquery and execute it. The result table lists two employee SSN values for employees that worked more than 10 hours on project #1.Substitute the project number into the IN operator list for the intermediate subquery and execute it. The result table lists two employee SSN values for employees that worked more than 10 hours on project #1. /* SQL Example 7.13 */ SELECT work_emp_ssn FROM assignment WHERE work_hours > 10 AND work_pro_number IN (1); work_emp_ssn ––––-------- 999111111 999888888

78 Bordoloi and Bock Understanding Nested Subqueries Contd. Now, substitute these two social security numbers into the IN operator listing for the outer query in place of the subquery.Now, substitute these two social security numbers into the IN operator listing for the outer query in place of the subquery. /* SQL Example 7.14 */ SELECT CAST(emp_last_name As CHAR(12)) "Last Name", CAST(emp_first_name As CHAR(12)) "First Name" FROM employee WHERE emp_ssn IN (999111111, 999888888); Last Name First Name ––––-------- ---––––------ Bock Douglas Prescott Sherri

79 Bordoloi and Bock SUBQUERIES AND COMPARISON OPERATORS The general form of the WHERE clause with a comparison operator is similar to that used thus far in the text.The general form of the WHERE clause with a comparison operator is similar to that used thus far in the text. Note that the syntax for the subquery is to be enclosed by parentheses.Note that the syntax for the subquery is to be enclosed by parentheses. WHERE (subquery)

80 Bordoloi and Bock SUBQUERIES AND COMPARISON OPERATORS Contd. The most important point to remember when using a subquery with a comparison operator is that the subquery can only return a single or scalar value.The most important point to remember when using a subquery with a comparison operator is that the subquery can only return a single or scalar value. This is also termed a scalar subquery because a single column of a single row is returned by the subquery.This is also termed a scalar subquery because a single column of a single row is returned by the subquery. If a subquery returns more than one value, the SQL Server will generate the Msg 512: Subquery returned more than 1 row error message, and the query will fail to execute. If a subquery returns more than one value, the SQL Server will generate the Msg 512: Subquery returned more than 1 row error message, and the query will fail to execute.

81 Bordoloi and Bock Subquery Errors SQL Example 7.16 violates the "single value" rule – this subquery returns multiple values for the emp_salary column.SQL Example 7.16 violates the "single value" rule – this subquery returns multiple values for the emp_salary column. /* SQL Example 7.16 */ SELECT emp_ssn FROM employee WHERE emp_salary > (SELECT emp_salary FROM employee WHERE emp_salary > 40000); Server: Msg 512, Level 16, State 1, Line 2 Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=,, >= or when the subquery is used as an expression.

82 Bordoloi and Bock Aggregate Functions and Comparison Operators The aggregate functions (AVG, SUM, MAX, MIN, and COUNT) always return a scalar result table.The aggregate functions (AVG, SUM, MAX, MIN, and COUNT) always return a scalar result table. Thus, a subquery with an aggregate function as the object of a comparison operator will always execute provided you have formulated the query properly.Thus, a subquery with an aggregate function as the object of a comparison operator will always execute provided you have formulated the query properly. Consider a situation where a payroll manager needs an employee listing with a salary level greater than the average salary level for all employees.Consider a situation where a payroll manager needs an employee listing with a salary level greater than the average salary level for all employees.

83 Bordoloi and Bock AVG Aggregate Function /* SQL Example 7.17 */ SELECT CAST(emp_last_name As CHAR(12)) "Last Name", CAST(emp_first_name As CHAR(12)) "First Name", '$' CONVERT (CHAR (10), emp_salary, 1) "Salary" FROM employee WHERE emp_salary > (SELECT AVG(emp_salary) FROM employee); Last Name First Name Salary ––––-------- ––––--------- –––-—------ Joshi Dinesh $ 38,000.00 Zhu Waiman $ 43,000.00 Joyner Suzanne $ 43,000.00 Bordoloi Bijoy $ 55,000.00

84 Bordoloi and Bock Comparison Operators Modified with the ALL or ANY Keywords The ALL and ANY keywords modify a comparison operator to allow an outer query to accept multiple values from a subquery.The ALL and ANY keywords modify a comparison operator to allow an outer query to accept multiple values from a subquery. The ALL keyword modifies the greater than comparison operator to mean greater than all values.The ALL keyword modifies the greater than comparison operator to mean greater than all values. The general form of the WHERE clause for this type of query is shown here.The general form of the WHERE clause for this type of query is shown here. WHERE WHERE [ALL | ANY] (subquery) [ALL | ANY] (subquery) Subqueries that use these keywords may also include GROUP BY and HAVING clauses.Subqueries that use these keywords may also include GROUP BY and HAVING clauses.

85 Bordoloi and Bock An ALL Keyword Example List all employees with a salary larger than the largest salary for an employee in dept 7.List all employees with a salary larger than the largest salary for an employee in dept 7. /* SQL Example 7.18 */ SELECT CAST(emp_last_name As CHAR(12)) "Last Name", CAST(emp_first_name As CHAR(12)) "First Name", '$' + CONVERT (CHAR (10), emp_salary, 1) "Salary" FROM employee WHERE emp_salary > ALL (SELECT emp_salary FROM employee WHERE emp_dpt_number = 7); Last Name First Name Salary ––––-------- ––––--------- –––—------- Bordoloi Bijoy $ 55,000.00

86 Bordoloi and Bock An ALL Keyword Example Cont. Conceptually, for each row in the employee table, the inner query creates a list of employee salaries for those in department 7. The outer query finds the largest salary for department 7 – $43,000 – only Bordoloi has a larger salary.Conceptually, for each row in the employee table, the inner query creates a list of employee salaries for those in department 7. The outer query finds the largest salary for department 7 – $43,000 – only Bordoloi has a larger salary. /* SQL Example 7.19 */ SELECT emp_salary FROM employee WHERE emp_dpt_number = 7; emp_salary –––––––-------------- 30000.0000 38000.0000 43000.0000 25000.0000

87 Bordoloi and Bock The ANY Keyword The ANY keyword is not as restrictive as the ALL keyword.The ANY keyword is not as restrictive as the ALL keyword. When used with the greater than comparison operator, "> ANY" means greater than some value. When used with the greater than comparison operator, "> ANY" means greater than some value. Management needs the employee name and salary of any employee with a salary greater than that of any employee with a salary that exceeds $30,000.Management needs the employee name and salary of any employee with a salary greater than that of any employee with a salary that exceeds $30,000.

88 Bordoloi and Bock The ANY Keyword Example /* SQL Example 7.20 */ SELECT CAST(emp_last_name As CHAR(12)) "Last Name", CAST(emp_first_name As CHAR(12)) "First Name", '$' + CONVERT (CHAR (10), emp_salary, 1) "Salary" FROM employee WHERE emp_salary > ANY (SELECT emp_salary FROM employee WHERE emp_salary > 30000); Last Name First Name Salary ––––-------- ––––--------- –––—------- Zhu Waiman $ 43,000.00 Joyner Suzanne $ 43,000.00 Bordoloi Bijoy $ 55,000.00

89 Bordoloi and Bock An "= ANY" (Equal Any) Example The "= ANY" operator is exactly equivalent to the IN operator.The "= ANY" operator is exactly equivalent to the IN operator. For example, to find the names of employees that have male dependents, you can use either IN or "= ANY" – SQL Examples 7.22 and 7.23 will produce an identical result table.For example, to find the names of employees that have male dependents, you can use either IN or "= ANY" – SQL Examples 7.22 and 7.23 will produce an identical result table. /* SQL Example 7.22 */ SELECT CAST(emp_last_name As CHAR(12)) "Last Name", CAST(emp_first_name As CHAR(12)) "First Name" FROM employee WHERE emp_ssn IN (SELECT dep_emp_ssn FROM dependent WHERE dep_gender = 'M');

90 Bordoloi and Bock An "= ANY" (Equal Any) Example Cont. /* SQL Example 7.23 */ SELECT CAST(emp_last_name As CHAR(12)) "Last Name", CAST(emp_first_name As CHAR(12)) "First Name" FROM employee WHERE emp_ssn = ANY (SELECT dep_emp_ssn FROM dependent WHERE dep_gender = 'M'); Last Name First Name ––––-------- ––––--------- Bock Douglas Zhu Waiman Joyner Suzanne

91 Bordoloi and Bock A "!= ANY" (Not Equal Any) Example Contd. While the "= ANY" is identical to the IN operator, the "!= ANY" (not equal any) is not equivalent to the NOT IN operator.While the "= ANY" is identical to the IN operator, the "!= ANY" (not equal any) is not equivalent to the NOT IN operator. If a subquery of employee salaries produces an intermediate result table with the salaries $38,000, $43,000, and $55,000, then the WHERE clause shown here means "NOT $38,000" AND "NOT $43,000" AND "NOT $55,000".If a subquery of employee salaries produces an intermediate result table with the salaries $38,000, $43,000, and $55,000, then the WHERE clause shown here means "NOT $38,000" AND "NOT $43,000" AND "NOT $55,000". WHERE NOT IN (38000, 43000, 55000);

92 Bordoloi and Bock A "!= ANY" (Not Equal Any) Example Contd. However, the "!= ANY" comparison operator and keyword combination shown in this next WHERE clause means "NOT $38,000" OR "NOT $43,000" OR "NOT $55,000".However, the "!= ANY" comparison operator and keyword combination shown in this next WHERE clause means "NOT $38,000" OR "NOT $43,000" OR "NOT $55,000". WHERE != ANY (38000, 43000, 55000);

93 Bordoloi and Bock An Erroneous != ANY Subquery This query tries to produce a listing of employees with no dependents; however the query fails – all employees of the firm will be listed because each emp_ssn in the employee table will NOT match at least one dep_emp_ssn in the dependent table.This query tries to produce a listing of employees with no dependents; however the query fails – all employees of the firm will be listed because each emp_ssn in the employee table will NOT match at least one dep_emp_ssn in the dependent table. /* SQL Example 7.24 */ SELECT CAST(emp_last_name As CHAR(12)) “Last Name”, CAST(emp_first_name As CHAR(12)) “First Name” FROM employee WHERE emp_ssn != ANY (SELECT DISTINCT dep_emp_ssn FROM dependent);

94 Bordoloi and Bock Solution – Use the NOT IN Operator These employees have no dependents. /* SQL Example 7.25 */ SELECT CAST(emp_last_name As CHAR(12)) "Last Name", CAST(emp_first_name As CHAR(12)) "First Name" FROM employee WHERE emp_ssn NOT IN (SELECT DISTINCT dep_emp_ssn FROM dependent); Last Name First Name ––––-------- ––––--------- Amin Hyder Joshi Dinesh Markis Marcia Prescott Sherri

95 Bordoloi and Bock CORRELATED SUBQUERIES A correlated subquery is one where the inner query depends on values provided by the outer query. This means the inner query is executed repeatedly, once for each row that might be selected by the outer query.This means the inner query is executed repeatedly, once for each row that might be selected by the outer query. Suppose management needs a listing of the most highly paid employee for each department.Suppose management needs a listing of the most highly paid employee for each department.

96 Bordoloi and Bock A Correlated Subquery Example The inner query references the outer query’s employee table with the alias e1, so e1.emp_dpt_number is treated like a variable—it changes as SQL Server examines each row of the employee table in the outer query. /* SQL Example 7.26 */ SELECT CAST(emp_last_name As CHAR(12)) "Last Name", CAST(emp_first_name As CHAR(12)) "First Name", emp_dpt_number "Dept", '$' + CONVERT (CHAR (10), emp_salary, 1) "Salary" FROM employee e1 WHERE emp_salary = (SELECT MAX(emp_salary) FROM employee WHERE emp_dpt_number = e1.emp_dpt_number);

97 Bordoloi and Bock Correlated Subquery Explanation Cont. The subquery in this SELECT statement cannot be resolved independently of the main query.The subquery in this SELECT statement cannot be resolved independently of the main query. The inner query compares the employee department number column (emp_dpt_number) of the employee table to the same column for the alias table name e1.The inner query compares the employee department number column (emp_dpt_number) of the employee table to the same column for the alias table name e1. The subquery's results are correlated with each individual row of the main query – thus, the term correlated subquery.The subquery's results are correlated with each individual row of the main query – thus, the term correlated subquery.

98 Bordoloi and Bock Subqueries and the EXISTS Operator When a subquery uses the EXISTS operator, the subquery functions as an existence test.When a subquery uses the EXISTS operator, the subquery functions as an existence test. The WHERE clause of the outer query tests for the existence of rows returned by the inner query.The WHERE clause of the outer query tests for the existence of rows returned by the inner query. The subquery does not actually produce any data; rather, it returns a value of TRUE or FALSE.The subquery does not actually produce any data; rather, it returns a value of TRUE or FALSE.

99 Bordoloi and Bock Subqueries and the EXISTS Operator Contd. The general format of a subquery WHERE clause with an EXISTS operator is shown here.The general format of a subquery WHERE clause with an EXISTS operator is shown here. Note that the NOT operator can also be used to negate the result of the EXISTS operator.Note that the NOT operator can also be used to negate the result of the EXISTS operator. WHERE [NOT] EXISTS (subquery)

100 Bordoloi and Bock An EXISTS Operator Example This correlated subquery also produces a listing of employees that have dependents.This correlated subquery also produces a listing of employees that have dependents. /* SQL Example 7.27 */ SELECT CAST(emp_last_name As CHAR(12)) "Last Name", CAST(emp_first_name As CHAR(12)) "First Name" FROM employee WHERE EXISTS (SELECT * FROM dependent WHERE emp_ssn = dep_emp_ssn); Last Name First Name ––––-------- ––––--------- Bock Douglas Zhu Waiman Joyner Suzanne Bordoloi Bijoy

101 Bordoloi and Bock Rules for Subqueries with the EXISTS Operator The keyword EXISTS is not preceded by a column name, constant, or other expression. The parameter in the SELECT clause of a subquery that uses an EXISTS operator almost always consists of an asterisk (*). This is because there is no real point in listing any column name because you are simply testing for the existence of rows that meet the conditions specified in the subquery. The subquery evaluates to TRUE or FALSE instead of returning any data. A subquery that uses an EXISTS operator always is a correlated subquery.

102 Bordoloi and Bock Other EXISTS Operator Facts The EXISTS operator is very important, because there is often no alternative to its use.The EXISTS operator is very important, because there is often no alternative to its use. All queries that use the IN operator or a modified comparison operator (=,, and so on, modified by ANY or ALL) can be expressed with the EXISTS operator.All queries that use the IN operator or a modified comparison operator (=,, and so on, modified by ANY or ALL) can be expressed with the EXISTS operator. Use of the EXISTS operator often produces a LESS efficient query than one that can be written in some other way. The next slide compares two subqueries—the first is more efficient. Can you determine why?Use of the EXISTS operator often produces a LESS efficient query than one that can be written in some other way. The next slide compares two subqueries—the first is more efficient. Can you determine why?

103 Bordoloi and Bock Comparing Two Subqueries /* SQL Example 7.28 */ SELECT emp_last_name FROM employee WHERE emp_ssn = ANY (SELECT dep_emp_ssn (SELECT dep_emp_ssn FROM dependent); FROM dependent); EMP_LAST_NAME-------------BockZhuJoyner /* SQL Example 7.29 */ SELECT emp_last_name FROM employee WHERE EXISTS (SELECT * (SELECT * FROM dependent FROM dependent WHERE emp_ssn = WHERE emp_ssn = dep_emp_ssn); dep_emp_ssn); EMP_LAST_NAME----------------BockZhuJoyner

104 Bordoloi and Bock Subqueries and the NOT EXISTS Operator The NOT EXISTS operator is the mirror-image of the EXISTS operator.The NOT EXISTS operator is the mirror-image of the EXISTS operator. A query that uses NOT EXISTS in the WHERE clause is satisfied if the subquery returns no rows.A query that uses NOT EXISTS in the WHERE clause is satisfied if the subquery returns no rows.

105 Bordoloi and Bock Subqueries and the ORDER BY Clause This SELECT statement orders the result table by emp_last_name, then emp_first_name.This SELECT statement orders the result table by emp_last_name, then emp_first_name. An ORDER BY clause must appear after the WHERE clause, and the subquery is considered to be part of the WHERE clause.An ORDER BY clause must appear after the WHERE clause, and the subquery is considered to be part of the WHERE clause. /* SQL Example 7.30 */ SELECT CAST(emp_last_name As CHAR(12)) "Last Name", CAST(emp_first_name As CHAR(12)) "First Name" FROM employee WHERE EXISTS (SELECT * FROM dependent WHERE emp_ssn = dep_emp_ssn) ORDER BY emp_last_name, emp_first_name;

106 Bordoloi and Bock Summary A subquery is simply a query inside another query as an object of the outer query’s WHERE clause.A subquery is simply a query inside another query as an object of the outer query’s WHERE clause. The data type produced by the subquery must be join compatible with the expression of the WHERE clause of the outer query.The data type produced by the subquery must be join compatible with the expression of the WHERE clause of the outer query. The IN, NOT IN, ALL, and ANY operators can modify the effect of a comparison operator.The IN, NOT IN, ALL, and ANY operators can modify the effect of a comparison operator. Aggregate functions require a subquery to return a scalar result table.Aggregate functions require a subquery to return a scalar result table. A correlated subquery is one where the inner query depends on values provided by the outer query.A correlated subquery is one where the inner query depends on values provided by the outer query. The EXISTS and NOT EXISTS operators test for row existence and return TRUE/FALSE values.The EXISTS and NOT EXISTS operators test for row existence and return TRUE/FALSE values. The ORDER BY clause placement must be after the WHERE clause of the outer query.The ORDER BY clause placement must be after the WHERE clause of the outer query.


Download ppt "Prentice Hall © 20041 COS 346 Day 14. 7-2 Agenda Questions?Questions? Assignment 5 CorrectedAssignment 5 Corrected –1 A, 1 B, 4 C’s, 1 F and 1 MIA Assignment."

Similar presentations


Ads by Google