93
COS 346 COS 346 Day 14 Day 14

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

  • View
    219

  • Download
    1

Embed Size (px)

Citation preview

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

COS 346COS 346

Day 14Day 14

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

AgendaAgenda• Questions?Questions?• Assignment 5 DueAssignment 5 Due• Assignment 6 Posted Assignment 6 Posted

– Due March 27 Due March 27 • Assignment 7 will be coming up soonAssignment 7 will be coming up soon

– Chap 7,8,9 & 10Chap 7,8,9 & 10– One assignment per week One assignment per week

• Capstone Project Proposals Due Capstone Project Proposals Due – ““You must advance your knowledge/skill level beyond that normally expected in the course.  It 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 is expected that the project will reflect a minimum of 30 hours of concentrated effort on your behalf. “behalf. “

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

• More on SQL & SQL ServerMore on SQL & SQL Server– Today we look at chap 7&8 in SQL Text Today we look at chap 7&8 in SQL Text – Sub-Queries & Views and Synonyms Sub-Queries & Views and Synonyms

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

Chapter 7: SubqueriesChapter 7: Subqueries

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

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

ObjectivesObjectives• Learn the formal subquery definition and write a Learn the formal subquery definition and write a

subquery.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 Write correlated subqueries including the EXISTS

operator.operator.• Use the ORDER BY clause in queries with a Use the ORDER BY clause in queries with a

subquery.subquery.

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

Example QueryExample 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 employeeWHERE emp_salary 25000 AND emp_dpt_number IN (3, 7);Last Name First Name Dept Salary––––-------- ––––-------- ––---- –––—--------Bock Douglas 7 $ 30,000.00Amin Hyder 3 $ 25,000.00Joshi Dinesh 7 $ 38,000.00more rows are displayed . . .

• Here the emp_salary and emp_dpt_number are known in advance.

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

Breaking a Query into SubtasksBreaking a Query into Subtasks• Management needs a list of employee names who Management needs a list of employee names who

earn a salary equal to the minimum salary paid to earn a salary equal to the minimum salary paid to any employee, and the minimum salary will any employee, and the minimum salary will certainly change over time. Step 1: Identify the certainly change over time. Step 1: Identify the minimum salary.minimum salary.

/* SQL Example 7.2 */

SELECT MIN(emp_salary) "Min Salary"

FROM employee;

Min Salary

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

25000.0000

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

Task 2: Writing the SubqueryTask 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 employeeWHERE 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

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

SUBQUERYSUBQUERY

• Formal Definition: The use of a SELECT Formal Definition: The use of a SELECT statement inside one of the clauses of statement inside one of the clauses of another SELECT statement, e.g., a another SELECT statement, e.g., a subquerysubquery is a query within a query. is a query within a query.

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

• The criteria values for a WHERE clause are The criteria values for a WHERE clause are unknown at design time.unknown at design time.

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

SUBQUERY TYPESSUBQUERY TYPES

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

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

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

SUBQUERY TYPESSUBQUERY TYPES

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

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

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

SUBQUERY – General RulesSUBQUERY – General Rules• A subquery SELECT statement is very similar to the A subquery SELECT statement is very similar to the

SELECT statement used to begin a regular or outer SELECT statement used to begin a regular or outer query. The complete syntax of a subquery is shown query. The complete syntax of a subquery is shown below.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] )

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

Clause RestrictionsClause Restrictions

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

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

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

Example of Join CompatibilityExample 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 employeeWHERE emp_ssn IN (SELECT dep_emp_ssn FROM dependent);

Last Name First Name ––––----- ––-------- Bock Douglas Zhu Waiman Joyner Suzanne Bordoloi Bijoy

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

Data-Type Join CompatibilityData-Type Join Compatibility

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

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

• Example: It would make no sense to compare Example: It would make no sense to compare the the emp_ssnemp_ssn column to the column to the dep_date_of_birthdep_date_of_birth column.column.

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

Data-Type Join Compatibility Contd.Data-Type Join Compatibility Contd.

• SQL Server maps ANSI standard data SQL Server maps ANSI standard data types to T-SQL data types.types to T-SQL data types.

• Conversion is automatic among any of Conversion is automatic among any of these ANSI numeric data types when these ANSI numeric data types when making numeric comparisons: making numeric comparisons:

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

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

Data-Type Join Compatibility Contd.Data-Type Join Compatibility Contd.

• SQL Server does not make comparisons SQL Server does not make comparisons based on column names.based on column names.

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

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

Other RestrictionsOther Restrictions

There are additional restrictions for subqueries. There are additional restrictions for subqueries. • The DISTINCT keyword The DISTINCT keyword cannotcannot be used in be used in

subqueries that include a GROUP BY clause. subqueries that include a GROUP BY clause. • Subqueries cannot manipulate their results Subqueries cannot manipulate their results

internally. This means that a subquery cannot internally. This means that a subquery cannot include the ORDER BY clause (unless a TOP include the ORDER BY clause (unless a TOP keyword is in the SELECT clause), the keyword is in the SELECT clause), the COMPUTE clause, or the INTO keyword.COMPUTE clause, or the INTO keyword.

• A result table can only include columns from a A result table can only include columns from a table named in the outer query’s FROM clause.table named in the outer query’s FROM clause.

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

SUBQUERIES AND THE IN OperatorSUBQUERIES AND THE IN Operator

• Here, a subquery produces a list of values Here, a subquery produces a list of values for the subquery result table.for the subquery result table.

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

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

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

IN Operator ExampleIN 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

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

Understanding the IN Operator Understanding the IN Operator with Subquerieswith Subqueries

• Conceptually, this SELECT statement is Conceptually, this SELECT statement is evaluated in two steps. First, the inner query evaluated in two steps. First, the inner query returns the identification numbers of those returns the identification numbers of those employees that have male dependents.employees that have male dependents.

/* SQL Example 7.7 */SELECT dep_emp_ssnFROM dependentWHERE dep_gender 'M';

dep_emp_ssn–––—-------999111111999444444999555555

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

Understanding the IN Operator Understanding the IN Operator with Subqueries Cont.with Subqueries Cont.

• Next, the list of social security number values is substituted Next, the list of social security number values is substituted into the outer query as the object of the IN operator. into the outer query as the object of the IN operator. Conceptually, the outer query now looks like the following.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

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

Comparing a Subquery to a Join QueryComparing 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 DouglasZhu WaimanJoyner Suzanne

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

When to Use a Subquery vs. a Join QueryWhen 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.

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

The NOT IN OperatorThe NOT IN Operator

• Like the IN operator, the NOT IN operator can take Like the IN operator, the NOT IN operator can take the result of a subquery as the operator object. 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 employeeWHERE emp_ssn NOT IN (SELECT dep_emp_ssn FROM dependent);

Last Name First Name ––––-------- –--------–––- Amin Hyder Joshi Dinesh Markis Marcia Prescott Sherri

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

The NOT IN Operator Contd.The NOT IN Operator Contd.

• The inner query in SQL Example 7.10 produces The inner query in SQL Example 7.10 produces an intermediate result table containing the social an intermediate result table containing the social security numbers of employees who have security numbers of employees who have dependents in the dependents in the dependentdependent table. table.

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

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

MULTIPLE LEVELS OF NESTINGMULTIPLE LEVELS OF NESTING

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

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

• SQL Server has no practical limit on the number SQL Server has no practical limit on the number of queries that can be nested in a WHERE clause.of queries that can be nested in a WHERE clause.

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

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

Nested Subquery ExampleNested 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 employeeWHERE 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

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

Understanding Nested SubqueriesUnderstanding Nested Subqueries

• In order to understand this subquery’s execution, In order to understand this subquery’s execution, begin your examination with the lowest subquery.begin your examination with the lowest subquery.

• Executing it independently of the outer queries Executing it independently of the outer queries produces the following scalar result table.produces the following scalar result table.

/* SQL Example 7.12 */

SELECT pro_number

FROM project

WHERE pro_name = 'Order Entry';

pro_number

–––-------

1

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

Understanding Nested Subqueries Understanding Nested Subqueries Contd.Contd.

• Substitute the project number into the IN operator list for Substitute the project number into the IN operator list for the intermediate subquery and execute it. The result table the intermediate subquery and execute it. The result table lists two employee SSN values for employees that worked lists two employee SSN values for employees that worked more than 10 hours on project #1.more than 10 hours on project #1.

/* SQL Example 7.13 */SELECT work_emp_ssnFROM assignmentWHERE work_hours > 10 AND work_pro_number IN (1);

work_emp_ssn––––--------999111111999888888

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

Understanding Nested Subqueries Understanding Nested Subqueries Contd.Contd.

• Now, substitute these two social security numbers Now, substitute these two social security numbers into the IN operator listing for the outer query in into the IN operator listing for the outer query in place of the subquery.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 employeeWHERE emp_ssn IN (999111111, 999888888);

Last Name First Name––––-------- ---––––------Bock DouglasPrescott Sherri

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

SUBQUERIES AND COMPARISON SUBQUERIES AND COMPARISON OPERATORSOPERATORS

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

• Note that the syntax for the subquery is to be Note that the syntax for the subquery is to be enclosed by parentheses. enclosed by parentheses.

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

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

SUBQUERIES AND COMPARISON SUBQUERIES AND COMPARISON OPERATORS Contd.OPERATORS Contd.

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

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

• If a subquery returns more than one value, the If a subquery returns more than one value, the SQL Server will generate the SQL Server will generate the Msg 512: Subquery Msg 512: Subquery returned more than 1 rowreturned more than 1 row error message, and the error message, and the query will fail to execute. query will fail to execute.

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

Subquery Errors Subquery Errors

• SQL Example 7.16 violates the "single value" rule – this SQL Example 7.16 violates the "single value" rule – this subquery returns multiple values for the subquery returns multiple values for the emp_salaryemp_salary column.column.

/* SQL Example 7.16 */SELECT emp_ssnFROM employeeWHERE 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.

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

Aggregate Functions and Comparison Aggregate Functions and Comparison OperatorsOperators

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

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

• Consider a situation where a payroll manager needs Consider a situation where a payroll manager needs an employee listing with a salary level greater than an employee listing with a salary level greater than the average salary level for all employees.the average salary level for all employees.

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

AVG Aggregate FunctionAVG 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 employeeWHERE emp_salary > (SELECT AVG(emp_salary) FROM employee);

Last Name First Name Salary––––-------- ––––--------- –––-—------Joshi Dinesh $ 38,000.00Zhu Waiman $ 43,000.00Joyner Suzanne $ 43,000.00Bordoloi Bijoy $ 55,000.00

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

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

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

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

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

WHERE <expression> <comparison_operator> WHERE <expression> <comparison_operator>

[ALL | ANY] (subquery)[ALL | ANY] (subquery)

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

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

An ALLAn ALL Keyword ExampleKeyword Example

• List List allall employees with a salary larger than the largest employees with a salary larger than the largest salary for an employee in dept 7.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 employeeWHERE emp_salary > ALL (SELECT emp_salary FROM employee WHERE emp_dpt_number = 7);

Last Name First Name Salary ––––-------- ––––--------- –––—------- Bordoloi Bijoy $ 55,000.00

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

An ALLAn ALL Keyword Example Cont.Keyword Example Cont.• Conceptually, for each row in the Conceptually, for each row in the employeeemployee table, the table, the

inner query creates a list of employee salaries for inner query creates a list of employee salaries for those in department 7. The outer query finds the those in department 7. The outer query finds the largest salary for department 7 – $43,000 – only largest salary for department 7 – $43,000 – only Bordoloi has a larger salary.Bordoloi has a larger salary.

/* SQL Example 7.19 */SELECT emp_salaryFROM employeeWHERE emp_dpt_number = 7;

emp_salary–––––––--------------30000.000038000.000043000.000025000.0000

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

The ANY KeywordThe ANY Keyword

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

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

• Management needs the employee name and Management needs the employee name and salary of any employee with a salary greater salary of any employee with a salary greater than that of any employee with a salary that than that of any employee with a salary that exceeds $30,000. exceeds $30,000.

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

The ANY Keyword ExampleThe 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 employeeWHERE emp_salary > ANY (SELECT emp_salary FROM employee WHERE emp_salary > 30000); Last Name First Name Salary––––-------- ––––--------- –––—-------Zhu Waiman $ 43,000.00Joyner Suzanne $ 43,000.00Bordoloi Bijoy $ 55,000.00

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

An "= ANY" (Equal Any) ExampleAn "= ANY" (Equal Any) Example• The "= ANY" operator is exactly equivalent toThe "= ANY" operator is exactly equivalent to the IN the IN

operator. operator. • For example, to find the names of employees that have For example, to find the names of employees that have

male dependents, you can use either IN or "= ANY" – male dependents, you can use either IN or "= ANY" – SQL Examples 7.22 and 7.23 will produce an identical SQL Examples 7.22 and 7.23 will produce an identical result table.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 employeeWHERE emp_ssn IN (SELECT dep_emp_ssn FROM dependent WHERE dep_gender = 'M');

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

An "= ANY" (Equal Any) Example Cont.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 employeeWHERE emp_ssn = ANY (SELECT dep_emp_ssn FROM dependent WHERE dep_gender = 'M');

Last Name First Name––––-------- ––––---------Bock DouglasZhu WaimanJoyner Suzanne

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

A "!= ANY" (Not Equal Any) Example A "!= ANY" (Not Equal Any) Example Contd.Contd.

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

• If a subquery of employee salaries produces an If a subquery of employee salaries produces an intermediate result table with the salaries $38,000, intermediate result table with the salaries $38,000, $43,000, and $55,000, then the WHERE clause $43,000, and $55,000, then the WHERE clause shown here means "NOT $38,000" AND "NOT shown here means "NOT $38,000" AND "NOT $43,000" AND "NOT $55,000".$43,000" AND "NOT $55,000".

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

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

A "!= ANY" (Not Equal Any) Example A "!= ANY" (Not Equal Any) Example Contd.Contd.

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

WHERE != ANY (38000, 43000, 55000);

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

An Erroneous != ANY SubqueryAn Erroneous != ANY Subquery

• This query tries to produce a listing of employees This query tries to produce a listing of employees with no dependents; however the query fails – all with no dependents; however the query fails – all employees of the firm will be listed because each employees of the firm will be listed because each emp_ssnemp_ssn in the in the employeeemployee table will NOT match at table will NOT match at least one least one dep_emp_ssndep_emp_ssn in the in the dependentdependent table. 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);

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

Solution – Use the NOT IN OperatorSolution – 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 employeeWHERE emp_ssn NOT IN (SELECT DISTINCT dep_emp_ssn FROM dependent);

Last Name First Name––––-------- ––––---------Amin HyderJoshi DineshMarkis MarciaPrescott Sherri

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

CORRELATED SUBQUERIESCORRELATED SUBQUERIES

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

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

• Suppose management needs a listing of the most Suppose management needs a listing of the most highly paid employee for each department.highly paid employee for each department.

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

A Correlated Subquery ExampleA 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);

  

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

Correlated Subquery Explanation Cont.Correlated Subquery Explanation Cont.

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

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

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

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

Subqueries and the EXISTS OperatorSubqueries and the EXISTS Operator

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

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

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

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

Subqueries and the EXISTS Operator Subqueries and the EXISTS Operator Contd.Contd.

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

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

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

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

An EXISTS Operator ExampleAn EXISTS Operator Example• This correlated subquery also produces a listing of This correlated subquery also produces a listing of

employees that have dependents.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 employeeWHERE EXISTS (SELECT * FROM dependent WHERE emp_ssn = dep_emp_ssn);

Last Name First Name––––-------- ––––---------Bock DouglasZhu WaimanJoyner SuzanneBordoloi Bijoy

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

Rules for Subqueries with the EXISTS Rules for Subqueries with the EXISTS OperatorOperator

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

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

Other EXISTS Operator FactsOther EXISTS Operator Facts

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

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

• Use of the EXISTS operator often produces a Use of the EXISTS operator often produces a LESS efficient query than one that can be LESS efficient query than one that can be written in some other way. The next slide written in some other way. The next slide compares two subqueries—the first is more compares two subqueries—the first is more efficient. Can you determine why?efficient. Can you determine why?

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

Comparing Two Subqueries Comparing Two Subqueries

/* SQL Example 7.28 *//* SQL Example 7.28 */SELECT emp_last_nameSELECT emp_last_nameFROM employeeFROM employeeWHERE emp_ssn = ANYWHERE emp_ssn = ANY (SELECT dep_emp_ssn(SELECT dep_emp_ssn FROM dependent);FROM dependent);    

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

/* SQL Example 7.29 *//* SQL Example 7.29 */SELECT emp_last_nameSELECT emp_last_nameFROM employeeFROM employeeWHERE EXISTSWHERE EXISTS (SELECT *(SELECT * FROM dependentFROM dependent WHERE emp_ssn =WHERE emp_ssn = dep_emp_ssn);dep_emp_ssn);  EMP_LAST_NAMEEMP_LAST_NAME--------------------------------BockBockZhuZhuJoynerJoyner

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

Subqueries and the NOT EXISTS OperatorSubqueries and the NOT EXISTS Operator

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

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

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

Subqueries and the ORDER BY ClauseSubqueries and the ORDER BY Clause

• This SELECT statement orders the result table by This SELECT statement orders the result table by emp_last_name, then emp_first_name.emp_last_name, then emp_first_name.

• An ORDER BY clause must appear after the An ORDER BY clause must appear after the WHERE clause, and the subquery is considered to be WHERE clause, and the subquery is considered to be part of the WHERE clause.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 employeeWHERE EXISTS (SELECT * FROM dependent WHERE emp_ssn = dep_emp_ssn)ORDER BY emp_last_name, emp_first_name;

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

SummarySummary• A subquery is simply a query inside another query as an A subquery is simply a query inside another query as an

object of the outer query’s WHERE clause.object of the outer query’s WHERE clause.• The data type produced by the subquery must be join The data type produced by the subquery must be join

compatible with the expression of the WHERE clause of compatible with the expression of the WHERE clause of the outer query.the outer query.

• The IN, NOT IN, ALL, and ANY operators can modify the The IN, NOT IN, ALL, and ANY operators can modify the effect of a comparison operator.effect of a comparison operator.

• Aggregate functions require a subquery to return a scalar Aggregate functions require a subquery to return a scalar result table.result table.

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

• The EXISTS and NOT EXISTS operators test for row The EXISTS and NOT EXISTS operators test for row existence and return TRUE/FALSE values.existence and return TRUE/FALSE values.

• The ORDER BY clause placement must be after the The ORDER BY clause placement must be after the WHERE clause of the outer query.WHERE clause of the outer query.

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

Chapter 8: Views and Tables with Chapter 8: Views and Tables with IdentityIdentity

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

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

ObjectivesObjectives• 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.

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

VIEWSVIEWS• A database view is a A database view is a logical logical oror virtual table virtual table based on based on

a query. It is useful to think of a a query. It is useful to think of a viewview as a stored as a stored query that can contain columns from one or more query that can contain columns from one or more tables.tables.

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

VIEWS Cont.VIEWS Cont.

• Views are created through use of a CREATE Views are created through use of a CREATE VIEW command that incorporates use of the VIEW command that incorporates use of the SELECT statement. SELECT statement.

• Views are queried just like tables—to a Views are queried just like tables—to a system user, they appear to be tables. system user, they appear to be tables.

• View definitions and execution plans are View definitions and execution plans are stored in the SQL Server database – the data stored in the SQL Server database – the data for a view is gathered each time a view is for a view is gathered each time a view is queried.queried.

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

VIEWS Cont.VIEWS Cont.

• Why use views?Why use views?– Views are simple to use.Views are simple to use.– Views enable a system designer to custom Views enable a system designer to custom

model data in a database – a user’s “view.”model data in a database – a user’s “view.”– They provide a form of security by limiting They provide a form of security by limiting

access to columns certain employees need to access to columns certain employees need to access while other data, such as employee access while other data, such as employee salary figures are hidden.salary figures are hidden.

– Views can also be used to update one or more Views can also be used to update one or more tables.tables.

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

An Example CREATE VIEW CommandAn Example CREATE VIEW Command

• The columns are renamed from the table The columns are renamed from the table column names to match the way that system column names to match the way that system users think about the data. 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

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

Selecting from a ViewSelecting from a View

• Notice that the only columns in the query are those Notice that the only columns in the query are those defined as part of the view. Also, a view can be sorted defined as part of the view. Also, a view can be sorted with the ORDER BY clause just like a table.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 . . .

  

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

CREATE VIEW SyntaxCREATE VIEW Syntax

• The general syntax has several options as The general syntax has several options as shown here.shown here.

CREATE VIEW [ <database_name>.]

[< owner>.] view_name

[(column_name1 [,column_name2 ...

column_name_n ] ) ]

[WITH <view_attribute1>

[, view_attribute2,…view_attribute_n] ]

AS

SELECT

[ WITH CHECK OPTION ]

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

View Syntax RulesView Syntax Rules

• The database name and owner name specification The database name and owner name specification is optional.is optional.

• View names must comply with SQL Server View names must comply with SQL Server naming rules.naming rules.

• Columns included in a view can be optionally Columns included in a view can be optionally renamed. Renaming is required if:renamed. Renaming is required if:– a column is derived by an arithmetic expression, a column is derived by an arithmetic expression,

function, or constant.function, or constant.

– a JOIN causes the selection of two column from a JOIN causes the selection of two column from different tables with the same name—rename one of different tables with the same name—rename one of the columns.the columns.

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

View Syntax Rules Contd.View Syntax Rules Contd.• The AS keyword is required.The AS keyword is required.• The SELECT statement defines the columns in a The SELECT statement defines the columns in a

view.view.• The SELECT can select from one or more tables The SELECT can select from one or more tables

including a JOIN operation or select columns from including a JOIN operation or select columns from other views.other views.

• The SELECT cannot include:The SELECT cannot include:– COMPUTE or COMPUTE BY clauses.COMPUTE or COMPUTE BY clauses.– ORDER BY clauses unless TOP is used.ORDER BY clauses unless TOP is used.– The INTO keyword.The INTO keyword.– A temporary table or table variable.A temporary table or table variable.– More than 1,024 columns.More than 1,024 columns.

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

Example CREATE VIEW with Columns RenamedExample CREATE VIEW with Columns Renamed

/* SQL Example 8.3 */CREATE VIEW empview7 (SSN, FirstName, LastName, Dept) ASSELECT emp_ssn, emp_first_name, emp_last_name, emp_dpt_numberFROM employeeWHERE emp_dpt_number=7WITH CHECK OPTION

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

Selecting from Empview7Selecting from Empview7• The column names from the view are probably more The column names from the view are probably more

meaningful to system users than the original meaningful to system users than the original employeeemployee table column names.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

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

A View with the Same Structure as a TableA 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

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

Selecting from the Dept_ViewSelecting 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

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

FUNCTIONS AND VIEWS:FUNCTIONS AND VIEWS:JOIN VIEWSJOIN VIEWS

• Views can contain simple row functions Views can contain simple row functions and also JOIN tables.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

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

Selecting from the Dept_Salary ViewSelecting 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

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

DROPPING VIEWSDROPPING VIEWS

• A Database Administrator or View Owner A Database Administrator or View Owner can drop a view with the DROP VIEW can drop a view with the DROP VIEW statement.statement.

/* SQL Example 8.10 */

DROP VIEW dept_view;

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

View StabilityView Stability

• Views do not store data – only the view definition Views do not store data – only the view definition is stored, and view data is only temporary.is stored, and view data is only temporary.

• When a table underlying a view is dropped, the When a table underlying a view is dropped, the view becomes invalid.view becomes invalid.

• The server message for a SELECT from an invalid The server message for a SELECT from an invalid view is: view is: Msg 208, Procedure <view Msg 208, Procedure <view name>, Line #, Invalid Object name>, Line #, Invalid Object <table name>.<table name>.

• If the table is recreated, the view will again work If the table is recreated, the view will again work satisfactorily.satisfactorily.

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

INSERTING, UPDATING, and INSERTING, UPDATING, and DELETING ROWS THROUGH VIEWSDELETING ROWS THROUGH VIEWS

• Inserting and updating table rows through views is Inserting and updating table rows through views is complex; deleting rows is simpler.complex; deleting rows is simpler.

• To execute DML on a view, the view must be To execute DML on a view, the view must be updateable:updateable:– No aggregate functions are specified in the SELECT No aggregate functions are specified in the SELECT

list.list.– Cannot use the TOP, GROUP BY, DISTINCT, or Cannot use the TOP, GROUP BY, DISTINCT, or

UNION clauses.UNION clauses.– No derived columns in the SELECT list.No derived columns in the SELECT list.– Views created with a JOIN can only modify or insert Views created with a JOIN can only modify or insert

rows in one table at a time.rows in one table at a time.

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

Inserting RowsInserting Rows• The INSERT statement cannot violate any constraints on The INSERT statement cannot violate any constraints on

underlying tables.underlying tables.

• Here, the Here, the departmentdepartment table has four columns and the view only table has four columns and the view only has two columns, but the other two table columns can be has two columns, but the other two table columns can be

NULL.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');

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

Updating RowsUpdating Rows• The UPDATE statement updates existing rows through The UPDATE statement updates existing rows through

a view. Here, a department name is changed from a view. Here, a department name is changed from Department 20 to Department 19.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

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

Deleting RowsDeleting 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.0003 Admin and Records 999555555 2001-01-01 00:00:00.0007 Production 999444444 1998-05-22 00:00:00.000

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

TABLES and the IDENTITY PROPERTYTABLES and the IDENTITY PROPERTY

• Suppose a furniture store needs to generate unique Suppose a furniture store needs to generate unique numbers to identify sales orders – how are these numbers to identify sales orders – how are these numbers produced?numbers produced?

• Solution – let the computer generate them from a Solution – let the computer generate them from a sequence of numbers.sequence of numbers.

• SQL Server provides this capability through tables SQL Server provides this capability through tables that have a column defined with the that have a column defined with the IdentityIdentity property clause.property clause.

• The general syntax of the IDENTITY clause is:IDENTITY [ ( initial_value , increment ) ]

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

CREATE TABLE Syntax with CREATE TABLE Syntax with Identity ColumnIdentity Column

• The The sales_ordersales_order table example. table example.• The IDENTITY clause causes automatic generation The IDENTITY clause causes automatic generation

of of so_numberso_number column values with an initial value of column values with an initial value of 100 and increment of 1.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 );

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

Inserting Sales_Order RowsInserting Sales_Order Rows

• The INSERT statement shown here inserts three The INSERT statement shown here inserts three rows into the rows into the sales_ordersales_order table. table.

• Notice that a value is not inserted for the Notice that a value is not inserted for the so_numberso_number column. 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');

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

Selecting Sales_Order RowsSelecting Sales_Order Rows

• SQL Example 8.30 shows the results of the SQL Example 8.30 shows the results of the three INSERT statements.three INSERT statements.

/* SQL Example 8.30 */SELECT *FROM sales_order;so_number so_value so_emp_ssn–––—––––––– ––––—–––-– ––––––––––100 155.59 999111111101 450.00 999444444102 16.95 999444444

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

The Related Order_Details TableThe Related Order_Details Table

• The The sales_ordersales_order table is related in a one-to- table is related in a one-to-many fashion with the many fashion with the order_detailsorder_details table. table.

• The The order_detailsorder_details table has a table has a Composite Composite PRIMARY KEYPRIMARY KEY that includes the that includes the od_numberod_number and and od_rowod_row columns – columns – od_rowod_row is a way of numbering each item on an is a way of numbering each item on an order while order while od_number od_number is system generated is system generated and serves as a and serves as a FOREIGN KEYFOREIGN KEY link to the link to the sales_ordersales_order table. table.

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

The Related Order_Details Table Cont.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 );

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

Inserting Rows in Sales_Order and Inserting Rows in Sales_Order and Order_DetailsOrder_Details

• Assume the first two Assume the first two sales_ordersales_order rows have been rows have been deleted.deleted.

/* Insert a new sales_order row and two order_detail rows */

INSERT INTO sales_order VALUES(200.00, '999111111' );GOBEGIN 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

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

Inserting Rows in Sales_Order and Inserting Rows in Sales_Order and Order_Details Contd.Order_Details Contd.

• SQL Example 8.32 defines a variable with a SQL Example 8.32 defines a variable with a DECLARE statement -- DECLARE statement -- @so_number@so_number..

• The The SCOPE_IDENTITYSCOPE_IDENTITY function, a pre-defined function, a pre-defined SQL Server function returns from the database SQL Server function returns from the database system tables the value of the last identity number system tables the value of the last identity number generated by the system generated by the system withinwithin the same the same procedure—here the value for the PRIMARY procedure—here the value for the PRIMARY KEY for the new KEY for the new sales_ordersales_order row. row.

• The variable value of The variable value of @so_number@so_number is inserted into is inserted into the the order_detailsorder_details rows in order to create the rows in order to create the necessary referential integrity link.necessary referential integrity link.

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

Results of the Row InsertionsResults 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.00103 2 Table Lamp 2 50.00

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

Reviewing the Row InsertionsReviewing the Row Insertions

• The The IdentityIdentity property of the property of the so_numberso_number column column of the of the sales_ordersales_order table automatically generated table automatically generated the next identity number (the next identity number (103103). ).

• The The SCOPE_IDENTITYSCOPE_IDENTITY function enabled function enabled accessing this value from database system tables accessing this value from database system tables in order to insert the value into the in order to insert the value into the od_numberod_number column of the column of the order_detailsorder_details table. table.

• The two tables are linked through these columns The two tables are linked through these columns and their common values.and their common values.

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

SummarySummary• Views are an important mechanism to facilitate the Views are an important mechanism to facilitate the

display of selected table columns.display of selected table columns.• Views provide a form of database security by Views provide a form of database security by

limiting access to columns displayed.limiting access to columns displayed.• Views can be used for DML of underlying tables Views can be used for DML of underlying tables

if they are “updateable” views.if they are “updateable” views.• Identity columns can be used to generate primary Identity columns can be used to generate primary

key values automatically.key values automatically.• The SCOPE_IDENTITY property enables The SCOPE_IDENTITY property enables

retrieval of identity number values from database retrieval of identity number values from database system tables to enforce referential integrity system tables to enforce referential integrity between two or more tables.between two or more tables.