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

Preview:

Citation preview

Chapter 5More 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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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)

23

Figure 8.4

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

groups◦ Groups satisfying the conditions are selected

24

HAVING Clause

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

26

Figure 8.4

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)

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

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

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

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

Specifying Constraints

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

Constraints◦ Prevent the data from being made inconsistent by

any kind of statement Triggers

◦ Maintain database consistency and defined operationally

33

Constraints vs. Triggers

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

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

query

35

View Properties

◦ 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

◦ 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

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

38

Query on View

DROP VIEW WORKS_ON1;

39

DROP VIEW

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

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

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

43

Table: 8.1 (SQL Summary)

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

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

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

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

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

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

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

51

EMR

NursesPhysician Patient

Legal Agent

Accounting Auditor External service provides

Insurance Company

52

Accounts Receivable

Corporate Auditor

Insurance Company

Provide Clinical

Care

Comply with

Regulations

Auditor

physician nurse

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

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

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

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

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

Sequence diagram for closing the record use case

58

Recommended