Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "More SQL: Complex Queries, Triggers, Views, and Schema Modification 1."— Presentation transcript:

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

2  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

3  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

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

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

6  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

7  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

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

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

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

11  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

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

13  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

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

15  Join operations can be specified in FROM clause ◦ Understandability  Use AS construct to Rename join attributes  Default is inner join 15

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

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

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

19  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

20  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

21  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

22  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

23 23

24  Used with GROUP BY clause  Used as a condition on the sub-relations or groups ◦ Groups satisfying the conditions are selected 24

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

26 26

27  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

28  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

29  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

30  The processing steps ◦ 1) the WHERE Clause is executed to select individual tuples ◦ 2) HAVING clause executed to select individual groups of tuples 30

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

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

33  Constraints ◦ Prevent the data from being made inconsistent by any kind of statement  Triggers ◦ Maintain database consistency and defined operationally 33

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

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

36 ◦ CREAT VIEW WORKS_ON1 ◦ AS SELECT FNAME, LNAME, PNAME, HOURS  FROM EMPLOYEE, PROJECT, WORKS_ON  WHERE SSN=ESSN AND PNO=PNUMBER 36 FNAMELNAMEPNAMEHOURS WORKS_ON1 Defining tables

37 ◦ 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 DEPT_NAMETOTAL_SALNO_OF_EMPS DEPT_INFO

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

39  DROP VIEW WORKS_ON1; 39

40  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

41  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

42  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

43 43

44  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

45  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

46  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

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

48 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

49 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

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

51 51 EMR Nurses Physician Patient Legal Agent AccountingAuditor External service provides Insurance Company

52 52 Accounts Receivable Corporate Auditor Insurance Company Provide Clinical Care Comply with Regulations Auditor physician nurse

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

54  Basic Steps: 1.The user identifies him/herself to EMR 2.EMR verifies the user’s security access, permission, and so on 3.The user specifies the request to get the records for a patient 4.EMR provides the records to the user 5.If user wants to access additional records, go to step 3 54

55  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

56  Basic Steps: 1.All clinical records are examined for each patient to determine if the patient is deceased 2.For all deceased patients, the records are closed 3.For those who left, the records are added to records close schedule 4.All clinical records for closure are moved to the archive 56

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

58 58


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

Similar presentations


Ads by Google