Presentation is loading. Please wait.

Presentation is loading. Please wait.

Bordoloi and Bock COS 346 Day 14. Bordoloi and Bock Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted.

Similar presentations


Presentation on theme: "Bordoloi and Bock COS 346 Day 14. Bordoloi and Bock Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted."— Presentation transcript:

1 Bordoloi and Bock COS 346 Day 14

2 Bordoloi and Bock Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March 27 Assignment 7 will be coming up soonAssignment 7 will be coming up soon –Chap 7,8,9 & 10 –One assignment per week Capstone Project Proposals DueCapstone Project Proposals Due –“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 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. More on SQL & SQL ServerMore on SQL & SQL Server –Today we look at chap 7&8 in SQL Text –Sub-Queries & Views and Synonyms

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

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

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

6 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

7 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

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

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

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

11 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] )

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

13 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

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

15 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

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

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

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

19 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

20 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

21 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

22 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

23 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 join query when the existence of values must be checked with the EXISTS operator—a join query may perform better than a subquery. The EXISTS operator is discussed later in the chapter.

24 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

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

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

27 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

28 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

29 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

30 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

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

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

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

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

35 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

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

37 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

38 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

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

40 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

41 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');

42 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

43 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);

44 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);

45 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);

46 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

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

48 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);

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

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

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

52 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

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

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

55 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

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

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

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

59 Bordoloi and Bock Chapter 8: Views and Tables with Identity SQL for SQL Server Bijoy Bordoloi and Douglas Bock

60 Bordoloi and Bock Objectives Create a single table view. Create a join table view—include functions. Insert, update, and delete table rows using a view. Create a view with errors. Drop a view. Create a table with column specifications that include the identity property. Insert data rows into tables with a column specified with the identity property. Use SCOPE_IDENTITY function to insert data rows into tables related to a table that has a column specified with the identity property.

61 Bordoloi and Bock VIEWS A database view is a logical or virtual table based on a query. It is useful to think of a view as a stored query that can contain columns from one or more tables.A database view is a logical or virtual table based on a query. It is useful to think of a view as a stored query that can contain columns from one or more tables.

62 Bordoloi and Bock VIEWS Cont. Views are created through use of a CREATE VIEW command that incorporates use of the SELECT statement.Views are created through use of a CREATE VIEW command that incorporates use of the SELECT statement. Views are queried just like tables—to a system user, they appear to be tables.Views are queried just like tables—to a system user, they appear to be tables. View definitions and execution plans are stored in the SQL Server database – the data for a view is gathered each time a view is queried.View definitions and execution plans are stored in the SQL Server database – the data for a view is gathered each time a view is queried.

63 Bordoloi and Bock VIEWS Cont. Why use views?Why use views? –Views are simple to use. –Views enable a system designer to custom model data in a database – a user’s “view.” –They provide a form of security by limiting access to columns certain employees need to access while other data, such as employee salary figures are hidden. –Views can also be used to update one or more tables.

64 Bordoloi and Bock An Example CREATE VIEW Command The columns are renamed from the table column names to match the way that system users think about the data.The columns are renamed from the table column names to match the way that system users think about the data. /* SQL Example 8.1 */ CREATE VIEW employee_parking (parking_space, last_name, first_name, ssn) AS SELECT emp_parking_space, emp_last_name, emp_first_name, emp_ssn FROM employee

65 Bordoloi and Bock

66 Selecting from a View Notice that the only columns in the query are those defined as part of the view. Also, a view can be sorted with the ORDER BY clause just like a table.Notice that the only columns in the query are those defined as part of the view. Also, a view can be sorted with the ORDER BY clause just like a table. /* SQL Example 8.2 */ SELECT * FROM employee_parking ORDER BY last_name, first_name; parking_space last_name first_name ssn ––––-–––––––––– –––––––-––– -––––––––-––– –––––––-– 422 Amin Hyder 999222222 542 Bock Douglas 999111111 1 Bordoloi Bijoy 999666666 more rows will be displayed...

67 Bordoloi and Bock

68 CREATE VIEW Syntax The general syntax has several options as shown here.The general syntax has several options as shown here. CREATE VIEW [.] [.] view_name [(column_name1 [,column_name2... column_name_n ] ) ] [WITH [, view_attribute2,…view_attribute_n] ] AS SELECT [ WITH CHECK OPTION ]

69 Bordoloi and Bock View Syntax Rules The database name and owner name specification is optional.The database name and owner name specification is optional. View names must comply with SQL Server naming rules.View names must comply with SQL Server naming rules. Columns included in a view can be optionally renamed. Renaming is required if:Columns included in a view can be optionally renamed. Renaming is required if: –a column is derived by an arithmetic expression, function, or constant. –a JOIN causes the selection of two column from different tables with the same name—rename one of the columns.

70 Bordoloi and Bock View Syntax Rules Contd. The AS keyword is required.The AS keyword is required. The SELECT statement defines the columns in a view.The SELECT statement defines the columns in a view. The SELECT can select from one or more tables including a JOIN operation or select columns from other views.The SELECT can select from one or more tables including a JOIN operation or select columns from other views. The SELECT cannot include:The SELECT cannot include: –COMPUTE or COMPUTE BY clauses. –ORDER BY clauses unless TOP is used. –The INTO keyword. –A temporary table or table variable. –More than 1,024 columns.

71 Bordoloi and Bock Example CREATE VIEW with Columns Renamed /* SQL Example 8.3 */ CREATE VIEW empview7 (SSN, FirstName, LastName, Dept) AS SELECT emp_ssn, emp_first_name, emp_last_name, emp_dpt_number FROM employee WHERE emp_dpt_number=7 WITH CHECK OPTION

72 Bordoloi and Bock Selecting from Empview7 The column names from the view are probably more meaningful to system users than the original employee table column names.The column names from the view are probably more meaningful to system users than the original employee table column names. /* SQL Example 8.4 */ SELECT * FROM empview7; SSN FirstName LastName Dept ––––––––– –––––––––--––––– ––––--––––––––– ––––– 999111111 Douglas Bock 7 999333333 Dinesh Joshi 7 999444444 Waiman Zhu 7 999888888 Sherri Prescott 7

73 Bordoloi and Bock A View with the Same Structure as a Table The column names are more meaningful.The column names are more meaningful. The manager’s SSN is already formatted.The manager’s SSN is already formatted. /* SQL Example 8.5 */ CREATE VIEW dept_view (DepartmentNo, Name, ManagerSSN, StartDate) AS SELECT dpt_no, dpt_name, LEFT(dpt_mgrssn,3)+'-' +SUBSTRING(dpt_mgrssn,4,2)+'-'+ RIGHT(dpt_mgrssn,4), CAST(dpt_mgr_start_date As CHAR(11)) FROM department

74 Bordoloi and Bock Selecting from the Dept_View /* SQL Example 8.6 */ SELECT * FROM dept_view; DepartmentNo Name ManagerSSN StartDate –––––––––––— –––—–––––––—–––––– ––––––––––– ––––––––––– 1 Headquarters 999-66-6666 Jun 19 1981 3 Admin and Records 999-55-5555 Jan 1 2001 7 Production 999-44-4444 May 22 1998

75 Bordoloi and Bock FUNCTIONS AND VIEWS: JOIN VIEWS Views can contain simple row functions and also JOIN tables.Views can contain simple row functions and also JOIN tables. /* SQL Example 8.8 */ CREATE VIEW dept_salary (Name, MinSalary, MaxSalary, AvgSalary) AS SELECT d.dpt_name, MIN(e.emp_salary), MAX(e.emp_salary), AVG(e.emp_salary) FROM employee e JOIN department d ON (e.emp_dpt_number=d.dpt_no) GROUP BY d.dpt_name

76 Bordoloi and Bock Selecting from the Dept_Salary View /* SQL Example 8.9 */ SELECT * FROM dept_salary; Name MinSalary MaxSalary AvgSalary ––––––––––––––––— ––––——––-–– ––––––-–––– ––––––-––– Admin and Records 25000.0000 43000.0000 31000.0000 Headquarters 55000.0000 55000.0000 55000.0000 Production 25000.0000 43000.0000 34000.0000

77 Bordoloi and Bock DROPPING VIEWS A Database Administrator or View Owner can drop a view with the DROP VIEW statement.A Database Administrator or View Owner can drop a view with the DROP VIEW statement. /* SQL Example 8.10 */ DROP VIEW dept_view;

78 Bordoloi and Bock View Stability Views do not store data – only the view definition is stored, and view data is only temporary.Views do not store data – only the view definition is stored, and view data is only temporary. When a table underlying a view is dropped, the view becomes invalid.When a table underlying a view is dropped, the view becomes invalid. The server message for a SELECT from an invalid view is: Msg 208, Procedure, Line #, Invalid Object.The server message for a SELECT from an invalid view is: Msg 208, Procedure, Line #, Invalid Object. If the table is recreated, the view will again work satisfactorily.If the table is recreated, the view will again work satisfactorily.

79 Bordoloi and Bock INSERTING, UPDATING, and DELETING ROWS THROUGH VIEWS Inserting and updating table rows through views is complex; deleting rows is simpler.Inserting and updating table rows through views is complex; deleting rows is simpler. To execute DML on a view, the view must be updateable:To execute DML on a view, the view must be updateable: –No aggregate functions are specified in the SELECT list. –Cannot use the TOP, GROUP BY, DISTINCT, or UNION clauses. –No derived columns in the SELECT list. –Views created with a JOIN can only modify or insert rows in one table at a time.

80 Bordoloi and Bock Inserting Rows The INSERT statement cannot violate any constraints on underlying tables.The INSERT statement cannot violate any constraints on underlying tables. Here, the department table has four columns and the view only has two columns, but the other two table columns can be NULL.Here, the department table has four columns and the view only has two columns, but the other two table columns can be NULL. /* SQL Example 8.21 */ CREATE VIEW dept_view2 AS SELECT dpt_no, dpt_name FROM department /* SQL Example 8.22 */ INSERT INTO dept_view2 VALUES (18, 'Department 18'); INSERT INTO dept_view2 VALUES (19, 'Department 20');

81 Bordoloi and Bock Updating Rows The UPDATE statement updates existing rows through a view. Here, a department name is changed from Department 20 to Department 19.The UPDATE statement updates existing rows through a view. Here, a department name is changed from Department 20 to Department 19. /* SQL Example 8.24 */ UPDATE dept_view2 SET dpt_name = 'Department 19' WHERE dpt_no = 19; (1 row(s) affected) /* SQL Example 8.25 */ SELECT * FROM department; dpt_no dpt_name dpt_mgrssn dpt_mgr_start_date ––-––– ––––—–––––-–––––– –-–––––––– ––––––––––––––––––––––– 1 Headquarters 999666666 1981-06-19 00:00:00.000 3 Admin and Records 999555555 2001-01-01 00:00:00.000 7 Production 999444444 1998-05-22 00:00:00.000 18 Department 18 NULL NULL 19 Department 19 NULL NULL

82 Bordoloi and Bock Deleting Rows This example deletes rows for departments 18 and 19.This example deletes rows for departments 18 and 19. /* SQL Example 8.26 */ DELETE dept_view2 WHERE dpt_no = 18 OR dpt_no = 19; (2 row(s) affected) /* SQL Example 8.27 */ SELECT * FROM department; dpt_no dpt_name dpt_mgrssn dpt_mgr_start_date –––––– ––––––––––—–––––- –––––––—-- –––––-----------------– 1 Headquarters 999666666 1981-06-19 00:00:00.000 3 Admin and Records 999555555 2001-01-01 00:00:00.000 7 Production 999444444 1998-05-22 00:00:00.000

83 Bordoloi and Bock TABLES and the IDENTITY PROPERTY Suppose a furniture store needs to generate unique numbers to identify sales orders – how are these numbers produced?Suppose a furniture store needs to generate unique numbers to identify sales orders – how are these numbers produced? Solution – let the computer generate them from a sequence of numbers.Solution – let the computer generate them from a sequence of numbers. SQL Server provides this capability through tables that have a column defined with the Identity property clause.SQL Server provides this capability through tables that have a column defined with the Identity property clause. The general syntax of the IDENTITY clause is: IDENTITY [ ( initial_value, increment ) ]

84 Bordoloi and Bock CREATE TABLE Syntax with Identity Column The sales_order table example.The sales_order table example. The IDENTITY clause causes automatic generation of so_number column values with an initial value of 100 and increment of 1.The IDENTITY clause causes automatic generation of so_number column values with an initial value of 100 and increment of 1. /* SQL Example 8.28 */ CREATE TABLE sales_order ( so_number INTEGER IDENTITY(100,1) CONSTRAINT pk_sales_order PRIMARY KEY, so_value DECIMAL(9,2), so_emp_ssn CHAR(9), CONSTRAINT fk_so_emp_ssn FOREIGN KEY (so_emp_ssn) REFERENCES employee );

85 Bordoloi and Bock Inserting Sales_Order Rows The INSERT statement shown here inserts three rows into the sales_order table.The INSERT statement shown here inserts three rows into the sales_order table. Notice that a value is not inserted for the so_number column.Notice that a value is not inserted for the so_number column. /* SQL Example 8.29 */ INSERT INTO sales_order VALUES (155.59, '999111111'); INSERT INTO sales_order VALUES (450.00, '999444444'); INSERT INTO sales_order VALUES (16.95, '999444444');

86 Bordoloi and Bock Selecting Sales_Order Rows SQL Example 8.30 shows the results of the three INSERT statements.SQL Example 8.30 shows the results of the three INSERT statements. /* SQL Example 8.30 */ SELECT * FROM sales_order; so_number so_value so_emp_ssn –––—––––––– ––––—–––-– –––––––––– 100 155.59 999111111 101 450.00 999444444 102 16.95 999444444

87 Bordoloi and Bock The Related Order_Details Table The sales_order table is related in a one-to- many fashion with the order_details table.The sales_order table is related in a one-to- many fashion with the order_details table. The order_details table has a Composite PRIMARY KEY that includes the od_number and od_row columns – od_row is a way of numbering each item on an order while od_number is system generated and serves as a FOREIGN KEY link to the sales_order table.The order_details table has a Composite PRIMARY KEY that includes the od_number and od_row columns – od_row is a way of numbering each item on an order while od_number is system generated and serves as a FOREIGN KEY link to the sales_order table.

88 Bordoloi and Bock The Related Order_Details Table Cont. /* SQL Example 8.31 */ CREATE TABLE order_details ( od_number INTEGER, od_row INTEGER, od_product_desc VARCHAR(15), od_quantity_ordered INTEGER, od_product_price DECIMAL(9,2), CONSTRAINT pk_order_details PRIMARY KEY (od_number, od_row), CONSTRAINT fk_order_number FOREIGN KEY (od_number) REFERENCES sales_order );

89 Bordoloi and Bock Inserting Rows in Sales_Order and Order_Details Assume the first two sales_order rows have been deleted.Assume the first two sales_order rows have been deleted. /* Insert a new sales_order row and two order_detail rows */ INSERT INTO sales_order VALUES(200.00, '999111111' ); GO BEGIN DECLARE @so_number INTEGER SELECT @so_number = (SELECT SCOPE_IDENTITY() ) INSERT INTO order_details VALUES (@so_number, 1, 'End Table', 1, 100.00); INSERT INTO order_details VALUES (@so_number, 2, 'Table Lamp', 2, 50.00); END

90 Bordoloi and Bock Inserting Rows in Sales_Order and Order_Details Contd. SQL Example 8.32 defines a variable with a DECLARE statement -- @so_number.SQL Example 8.32 defines a variable with a DECLARE statement -- @so_number. The SCOPE_IDENTITY function, a pre-defined SQL Server function returns from the database system tables the value of the last identity number generated by the system within the same procedure—here the value for the PRIMARY KEY for the new sales_order row.The SCOPE_IDENTITY function, a pre-defined SQL Server function returns from the database system tables the value of the last identity number generated by the system within the same procedure—here the value for the PRIMARY KEY for the new sales_order row. The variable value of @so_number is inserted into the order_details rows in order to create the necessary referential integrity link.The variable value of @so_number is inserted into the order_details rows in order to create the necessary referential integrity link.

91 Bordoloi and Bock Results of the Row Insertions /* SQL Example 8.33 */ SELECT * FROM sales_order; so_number so_value so_emp_ssn –––-––––––– ––––-–––-– –––––––––– 103 200.00 999111111 /* SQL Example 8.34 */ SELECT od_number "So Number", od_row "Row", od_product_desc "Description", CAST(od_quantity_ordered As CHAR(3)) "Qty", od_product_price "Price" FROM order_details; So Number Row Description Qty Price –––—–––—––– –––-– ––—–––––––––– –––– –––––– 103 1 End Table 1 100.00 103 2 Table Lamp 2 50.00

92 Bordoloi and Bock Reviewing the Row Insertions The Identity property of the so_number column of the sales_order table automatically generated the next identity number (103).The Identity property of the so_number column of the sales_order table automatically generated the next identity number (103). The SCOPE_IDENTITY function enabled accessing this value from database system tables in order to insert the value into the od_number column of the order_details table.The SCOPE_IDENTITY function enabled accessing this value from database system tables in order to insert the value into the od_number column of the order_details table. The two tables are linked through these columns and their common values.The two tables are linked through these columns and their common values.

93 Bordoloi and BockSummary Views are an important mechanism to facilitate the display of selected table columns.Views are an important mechanism to facilitate the display of selected table columns. Views provide a form of database security by limiting access to columns displayed.Views provide a form of database security by limiting access to columns displayed. Views can be used for DML of underlying tables if they are “updateable” views.Views can be used for DML of underlying tables if they are “updateable” views. Identity columns can be used to generate primary key values automatically.Identity columns can be used to generate primary key values automatically. The SCOPE_IDENTITY property enables retrieval of identity number values from database system tables to enforce referential integrity between two or more tables.The SCOPE_IDENTITY property enables retrieval of identity number values from database system tables to enforce referential integrity between two or more tables.


Download ppt "Bordoloi and Bock COS 346 Day 14. Bordoloi and Bock Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted."

Similar presentations


Ads by Google