More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

58
Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification 1
  • date post

    22-Dec-2015
  • Category

    Documents

  • view

    223
  • download

    5

Transcript of More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Page 1: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Chapter 5More SQL: Complex Queries, Triggers,

Views, and Schema Modification

1

Page 2: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Some queries need the existing values in the database to be retrieved & compared◦ Nested queries are used to formulate such

queries In general, the query is evaluated from

bottom to top

2

Complex SQL Queries: Nested Queries

Page 3: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Make a list of Project numbers for projects that involve an employee whose last name is ‘Smith’, either as a worker or as a manger of the department that controls the project

3

Q4: Using Nested query

Page 4: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

SELECT DISTINCT PNUMBER FROM PROJECT

WHERE PNUMBER IN (SELECT PNUMBER

FROM DEPARTMENT, EMPLOYEE , PROJECT WHERE DNUM = DNUMBE AND MGRSSN = SSN AND LNAME = ‘Smith’)

OR PNUMBER IN

( SELECT PNO FROM WORKS_ON, EMPLOYEE WHERE ESSN=SSN AND LNAME = ‘Smith’);

4

Query Q4A: Using nested query

Page 5: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Query contains a reference to one or more columns in the outer query◦ When a condition in WHERE clause of a nested

query references attribute(s) of a relation defined in the outer query

The query is evaluated from top-to-the-bottom

5

Correlated nested queries

Page 6: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Get the name of each employee who has a dependent with the same first name and the same sex as the employee

SELECT E.FNAME, E.LNAME FROM EMPLOYEE AS E WHERE E.SSN IN (SELECT ESSN FROM DEPENDENT AS D WHERE E.FNAME=D.DEPENDENT_NAME

AND E.SEX=D.SEX);

6

Query 16:Example of Correlated query

Page 7: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

A nested query involving ‘=‘ or ‘IN’ can be replaced by a simple query

Get the name of each employee who has a dependent with the same first name and the same sex as the employee◦ SELECT E.FNAME,E.LNAME◦ FROM EMPLOYEE AS E, DEPEDENT AS D◦ WHERE E.SSN=D.ESSN AND

E.FNAME = D.DEPENDENT_NAME AND

E.SEX=D.SEX;

7

Q16B: Alternative Query

Page 8: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Get SSN of all employees who work on the same combination (project, hours) on some project that employee with SSN=‘123456789’

◦ SELECT DISTINCT ESSN◦ FROM WORKS_ON◦ WHERE (PNO, HOURS) IN (SELECT PNO, HOURS FROM WORKS_ON WHERE ESSN=‘123456789’);

8

Query involving Set comparison operators

Page 9: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Some comparison operators◦ ALL, ANY, SOME

Can be used with any other comparison operators◦ E.g.,

v> ALL V returns TRUE if v is greater than all values in the set V Suppose

v=25, and V = {12,14, 6, 8, 19}, then v> ALL V = TRUE

9

The keyword ALL

Page 10: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Get the names of all employees whose salary is greater than the salary of ALL the employees in the department 5◦ SELECT LNAME, FNAME◦ FROM EMPLOYEE◦ WHERE SALARY > ALL (SELECT SALARY FROM

EMPLOYEE WHERE DNO=5);

10

Example KEYWORD ALL

Page 11: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

EXISTS: ◦ Checks the result to see if a correlated nested

query is empty or not If the result (i.e., set) is empty it returns false If the result is Not empty it returns true

11

THE EXISTS AND NOT EXIST FUNCTIONS IN SQL

Page 12: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Find the name of each employee who has a dependent with the same first name and same sex as the employee

◦ SELECT E.FNAME, E.LNAME◦ FROM EMPLOYEE AS E◦ WHERE EXISTS (SELECT * ◦ FROM DEPENDENT AS D ◦ WHERE E.SSN= D. ESSN AND

E.SEX= D.SEX AND E.FNAME = D.DEPENT_NAME);

12

Query 16: example of EXISTS

Page 13: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Find the name of each employee who has NO dependent

◦ SELECT FNAME, LNAME◦ FROM EMPLOYEE E◦ WHERE NOT EXISTS ◦ (SELECT * ◦ FROM DEPENDENT ◦ WHERE E.SSN=ESSN);

13

Query 16: example of NOT EXISTS

Page 14: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Retrieve SSNs of all employees who work on project number 11,22,or 33◦ SELECT DISTINCT ESSN◦ FROM WORKS_ON◦ WHERE PNO IN (11,22,33)

14

Use of EXPLICIT SETS IN SQL

Page 15: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Join operations can be specified in FROM clause◦ Understandability

Use AS construct to Rename join attributes Default is inner join

15

Join (revisited): FROM CLAUSE

Page 16: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Find the name and address of employees who work in Research department

◦ SELECT FNAME, LNAME, ADDRESS◦ FROM (EMPLOYEE JOIN DEPARTMENT ON

DNO=DNUMBER)◦ WHERE DNAME = ‘Research’

16

Example 1: Join in FORM

Page 17: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Natural Join:◦ Builds an implicit join clause using common

columns in the two tables being joined The default is INNER join Example:

◦ SELECT FNAME, LNAME, ADDRESS◦ FROM ( EMPLOYEE NATURAL JOIN (DEPARTMENT

AS DEPT (DNAME, DNO, MSSN, MSDATE)))◦ WHERE DNAME =‘Research’;

17

Example 2: Renaming and NATURAL JOIN

Page 18: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

E.g.,◦ SELECT E.FNAME, E.LNAME◦ FROM EMPLOYEE AS E◦ WHERE E.SSN ◦ IN (SELECT ESSN FROM DEPENDENT ◦ WHERE ESSN=E.SSN AND

E.FNAM=DEPENDENT_NAME AND SEX=E.SEX

18

SCOPE of nested queries

Page 19: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Functions used to summarize information from multiple tuples into a single-tuple

E.g.,◦ COUNT ◦ SUM◦ MAX◦ MIN◦ AVG

The functions are used in SELECT or Having Clause

Aggregate Functions

Page 20: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Q20: Find the sum of the salaries of all employees in the ‘Research’ dept, as well as the max salary, the min salary, and average in that dept.

◦ SELECT SUM(SALARY), MAX(SALARY), MIN(SALARY) AVG(SALARY)

◦ FROM (EMPLOYEE NATURAL JOIN (DEPARTMENT AS DEPT(Dname, Dno, Mssn, Msdate)))

◦ WHERE DNAME=‘Research’

20

Aggregate Functions

Page 21: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

GROUP BY Clause ◦ Used to partition the relation into sub-relation◦ Works with aggregate functions (e.g., COUNT)◦ Grouping attribute

Grouping attribute (s) need to be specified in SELECT clause Create separate group for the grouping attribute with NULL

values

21

Example of grouping and COUNT

Page 22: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

For each department, retrieve the department number, the number of employees in the department, and their average salary◦SELECT DNO, COUNT(*), AVG(SALARY)◦FROM EMPLOYEE◦GROUP BY DNO; Figure.5.6.(a)

22

QUERY 24 (GROUP BY)

Page 23: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

23

Figure 8.4

Page 24: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Used with GROUP BY clause Used as a condition on the sub-relations or

groups◦ Groups satisfying the conditions are selected

24

HAVING Clause

Page 25: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

For each project on which more than two employees work, get the project number, the project name, the number of employees who work on the project◦ SELECT PNUMBER, PNAME, COUNT(*)◦ FROM PROJECT, WORKS_ON◦ WHERE PNUMBER=PNO◦ GROUP BY PNAME, PNUMBER◦ HAVING COUNT(*)>2;

25

Query 26

Page 26: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

26

Figure 8.4

Page 27: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Count the total number of employees whose salaries exceed $40,000 in each department, but only for department having more than five employees work

27

Q28: COUNT and HAVING Clauses (revisited)

Page 28: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

SELECT DNAME, COUNT (*) FROM DEPARTMENT, EMPLOYEE WHERE DNUMBER=DNO AND

SALARY>40000 GROUP BY DNAME HAVING COUNT (*)>5; Wrong

◦ Selects only department having more than 5 employees who ALL make more than 40K

28

Version 1: ?

Page 29: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

SELECT DNUMBER, COUNT (*) FROM DEPARTMENT, EMPLOYEE WHERE DNUMBER=DNO AND

SALARY>40000 AND DNO IN ◦ (SELECT DNO FROM EMPLOYEE

GROUP BY DNO ◦ HAVING COUNT(*)>5)

GROUP BY DNUMBER

29

Version 2: Correct One

Page 30: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

The processing steps◦ 1) the WHERE Clause is executed to select

individual tuples ◦ 2) HAVING clause executed to select individual

groups of tuples

30

Precedence rule

Page 31: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Create Assertion can be used to specify more general constraints that can NOT be specified by the built-in relational model constraints

Specifying Constraints

Page 32: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

To specify the constraint that the salary of an employee must not be greater than the salary of the manager of the department where the employee works for.

◦ CREATE ASSERTION SALARY_CONSTRAINT CHECK ( NOT EXISTS ( SELECT * FROM EMPLOYEE AS E, EMPLOYEE AS M, DEPARTMENTAS D WHERE E.SALARY > M. SALARY AND E.DNO=D.NUMBER AND D.MGRSSN=M.SSN));

32

Example of Assertion in SQL

Page 33: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Constraints◦ Prevent the data from being made inconsistent by

any kind of statement Triggers

◦ Maintain database consistency and defined operationally

33

Constraints vs. Triggers

Page 34: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

A view refers to a single table (or virtual table) that is derived from other tables (base tables)◦ Used as subroutine mechanism make a complex

query easier to understand easier to debug◦ Used as a flexible mechanism for access

CONTROL or Authorization mechanism to the data (discussed in ch24 security)

34

Views (Virtual Tables) in SQL

Page 35: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

A View is always up-to-date A view is realized at the time we execute a

query

35

View Properties

Page 36: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

◦ CREAT VIEW WORKS_ON1◦ AS SELECT FNAME, LNAME, PNAME, HOURS

FROM EMPLOYEE, PROJECT, WORKS_ON WHERE SSN=ESSN AND PNO=PNUMBER

36

Views in SQL

FNAME LNAME PNAME HOURS

WORKS_ON1

Defining tables

Page 37: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

◦ CREAT VIEW DEPT_INFO(DEPT_NAME, NO_OF_EMPS, TOTAL_SAL)

◦ AS SELECT DNAME, COUNT(*), SUM(SALARY) FROM EMPLOYEE, DEPARTMENT WHERE DNUMBER=DNO GROUP BY DNAME;

37

Example 2

DEPT_NAME TOTAL_SALNO_OF_EMPS

DEPT_INFO

Page 38: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

SELECT Fname, Lname FROM WORKS_ON1 WHERE Pname =‘ProjectX’;

38

Query on View

Page 39: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

DROP VIEW WORKS_ON1;

39

DROP VIEW

Page 40: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Two strategies to implement a view◦ Query modification

Maps the view into the base tables◦ View materialization

Create a temporary view table Uses incremental approach to keep a materialized

table up-date Removes the view table if it is not accessed for

certain period of time

40

View Implementation

Page 41: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Query on◦ SELECT Fname, Lname◦ FROM WORKS_ON1◦ WHERE Pname =‘ProjectX’;

Maps to◦ SELECT FNAME, LNAME,

FROM EMPLOYEE, PROJECT, WORKS_ON WHERE SSN=ESSN AND PNO=PNUMBER AND Pname =‘ProjectX’;

41

Example of Query Modification

Page 42: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Updating the views can be complicated and ambiguous

an update on a view defined on a single table without any aggregate functions can be mapped to an update on the base table

42

Updating of Views

Page 43: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

43

Table: 8.1 (SQL Summary)

Page 44: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

System development is a game that demands team work◦ Demands close collaboration of

Analysis Software development Database teams

UML◦ Standard language used for modeling business

and software application◦ Can be used by both application developer and

database engineer to communicate technical issues

44

Using the UML (Unified Modeling Language) to define requirements

Page 45: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

There are many types of UML diagrams to help DB designers

Diagrams can be used for ◦ Analysis◦ Design

Examples of diagrams◦ Use case◦ Class◦ Component◦ Etc.

45

UML Diagram for Database Design

Page 46: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Use case◦ used to model the system’s intended functions

and its environments◦ The model can be used as a contract between the

customer and the development

46

Diagrams

Page 47: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

The diagram contains◦ Actors

Anyone or any system that may use the system◦ Use case

Defines a series of actions , initiated by an actor, that the system performs

47

Use case diagrams: 1

Page 48: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Requirements definition: 1

48

A simple law of software development makes it important that we CLEARLY understand the desired capabilities and quality of a system◦ Understanding what we want to build before we

start to building it to reduce the risk of FAILURE

Page 49: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Requirements definition: 2

49

requirement definitions serve two goals◦ Establish the scope of the system we are to build◦ Establish a detailed understanding of the desired

capabilities of the system The major artifact that results from

requirements definition if we use UML is use case model of the system

Supporting the use case model are use case descriptions that elaborate the basic information and details flow of the use case

Page 50: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

One way to understand the information you obtain from the many players is to begin modeling their description or visualize the way the business works

Use case diagram◦ A diagram that shows use cases and their

relationships with actors and other use cases Actor:

An external person/system that uses the system Use case:

A complete flow of actions, initialed by an actor, that the system performs to provide some value to that actor

UML: concepts

50

Page 51: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

51

EMR

NursesPhysician Patient

Legal Agent

Accounting Auditor External service provides

Insurance Company

Page 52: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

52

Accounts Receivable

Corporate Auditor

Insurance Company

Provide Clinical

Care

Comply with

Regulations

Auditor

physician nurse

Page 53: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Use case Name: Access Clinical Records Use Case Purpose: The purpose of this use case is

to allow the clinical record information to be accessed by the authorized actors (i.e., users)

Precondition: user is authorized Post conditions: Clinical records will remain locked

until the clinical records user completes access and “releases” the clinical records.

Constraints: Only the same user to whom the records were released can change or return the records

Assumptions: None

53

Use Case Description: EMR

Page 54: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Basic Steps:1. The user identifies him/herself to EMR2. EMR verifies the user’s security access,

permission, and so on3. The user specifies the request to get the

records for a patient4. EMR provides the records to the user5. If user wants to access additional records, go

to step 3

54

Scenarios

Page 55: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Use case Name: close clinical records Use Case Purpose: The purpose of this use case is

to , allow no further updates. This places the specific records out of daily use

Precondition: the records must be archived Post conditions: the records removal schedule has

been completed Constraints: patient is deceased or left Assumptions: the archive system must maintain

the patient record for 7 years

55

Use Case Description: EMR

Page 56: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Basic Steps:1. All clinical records are examined for each

patient to determine if the patient is deceased2. For all deceased patients, the records are

closed3. For those who left, the records are added to

records close schedule4. All clinical records for closure are moved to the

archive

56

Scenarios

Page 57: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Sequence diagram◦A diagram of collaborating objects and the messages they send to each other

◦Arranged in time ordered◦Shows how use cases are implemented

UML: sequence diagram

57

Page 58: More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.

Sequence diagram for closing the record use case

58