Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 3 MORE SQL Copyright © 2004 Pearson Education, Inc.

Similar presentations


Presentation on theme: "Chapter 3 MORE SQL Copyright © 2004 Pearson Education, Inc."— Presentation transcript:

1 Chapter 3 MORE SQL Copyright © 2004 Pearson Education, Inc.

2 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Outline More Complex SQL Retrieval Queries Specifying Constraints as Assertions and Actions as Triggers Views in SQL Schema Change Statements in SQL Database Programming Slide 3 - 2

3 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition NULLS IN SQL QUERIES SQL allows queries that check if a value is NULL (missing or undefined or not applicable) SQL uses IS or IS NOT to compare NULLs because it considers each NULL value distinct from other NULL values, so equality comparison is not appropriate. Query 14: Retrieve the names of all employees who do not have supervisors. Q14:SELECT FNAME, LNAME FROMEMPLOYEE WHERESUPERSSN IS NULL Note: If a join condition is specified, tuples with NULL values for the join attributes are not included in the result Slide 3 - 3

4 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition NESTING OF QUERIES A complete SELECT query, called a nested query, can be specified within the WHERE-clause of another query, called the outer query Many of the previous queries can be specified in an alternative form using nesting Query 1: Retrieve the name and address of all employees who work for the 'Research' department. Q1:SELECTFNAME, LNAME, ADDRESS FROM EMPLOYEE WHEREDNO IN (SELECT DNUMBER FROMDEPARTMENT WHEREDNAME='Research' ) Slide 3 - 4

5 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition CORRELATED NESTED QUERIES If a condition in the WHERE-clause of a nested query references an attribute of a relation declared in the outer query, the two queries are said to be correlated The result of a correlated nested query is different for each tuple (or combination of tuples) of the relation(s) the outer query Query 12: Retrieve the name of each employee who has a dependent with the same first name as the employee. Q12: SELECT E.FNAME, E.LNAME FROMEMPLOYEE AS E WHEREE.SSN IN (SELECTESSN FROMDEPENDENT WHEREESSN=E.SSN AND E.FNAME=DEPENDENT_NAME) Slide 3 - 5

6 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition CORRELATED NESTED QUERIES (cont.) In Q12, the nested query has a different result for each tuple in the outer query A query written with nested SELECT... FROM... WHERE... blocks and using the = or IN comparison operators can always be expressed as a single block query. For example, Q12 may be written as in Q12A Q12A:SELECT E.FNAME, E.LNAME FROMEMPLOYEE E, DEPENDENT D WHEREE.SSN=D.ESSN AND E.FNAME=D.DEPENDENT_NAME Slide 3 - 6

7 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition THE EXISTS FUNCTION EXISTS is used to check whether the result of a correlated nested query is empty (contains no tuples) or not We can formulate Query 12 in an alternative form that uses EXISTS as Q12B below Slide 3 - 7

8 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition THE EXISTS FUNCTION (cont.) Query 12: Retrieve the name of each employee who has a dependent with the same first name as the employee. Q12B: SELECT FNAME, LNAME FROMEMPLOYEE WHEREEXISTS (SELECT* FROMDEPENDENT WHERESSN=ESSN AND FNAME=DEPENDENT_NAME) Slide 3 - 8

9 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition THE EXISTS FUNCTION (cont.) Query 6: Retrieve the names of employees who have no dependents. Q6:SELECT FNAME, LNAME FROMEMPLOYEE WHERENOT EXISTS (SELECT* FROM DEPENDENT WHERE SSN=ESSN) –In Q6, the correlated nested query retrieves all DEPENDENT tuples related to an EMPLOYEE tuple. If none exist, the EMPLOYEE tuple is selected –EXISTS is necessary for the expressive power of SQL Slide 3 - 9

10 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition More Comparison Operators … {=, >, >=, } {ANY, SOME, ALL} … Query 17: Retrieve all employees whose salary is greater than the salary of all employees in dept. 5 Q17: SELECT * FROMEmployee WHERE Salary > ALL (SELECT Salary FROM Employee WHERE DNO=5) Slide 3 - 10

11 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition EXPLICIT SETS It is also possible to use an explicit (enumerated) set of values in the WHERE-clause rather than a nested query Query 13: Retrieve the social security numbers of all employees who work on project number 1, 2, or 3. Q13:SELECT DISTINCT ESSN FROM WORKS_ON WHEREPNO IN (1, 2, 3) Slide 3 - 11

12 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Renaming of Attributes in SQL Rename any attribute that appears in the result of a query by adding the qualifier AS followed by the desired new name Q8A: SELECT E.Lname AS Employee_name, S.Lname AS Supervisor_name FROM EMPLOYEE AS E, EMPLOYEE AS S WHERE E.Super_ssn=S.Ssn Slide 3 - 12

13 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition SET OPERATIONS SQL has directly incorporated some set operations There is a union operation (UNION), and in some versions of SQL there are set difference (MINUS or EXCEPT) and intersection (INTERSECT) operations The resulting relations of these set operations are sets of tuples; duplicate tuples are eliminated from the result The set operations apply only to union compatible relations ; the two relations must have the same attributes and the attributes must appear in the same order Slide 3 - 13

14 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition SET OPERATIONS (cont.) Query 4: Make a list of all project numbers for projects that involve an employee whose last name is 'Smith' as a worker or as a manager of the department that controls the project. Q4:(SELECT PNAME FROMPROJECT, DEPARTMENT, EMPLOYEE WHEREDNUM=DNUMBER AND MGRSSN=SSN ANDLNAME='Smith') UNION(SELECT PNAME FROMPROJECT, WORKS_ON, EMPLOYEE WHEREPNUMBER=PNO AND ESSN=SSN AND LNAME='Smith') Slide 3 - 14

15 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition SET OPERATIONS (cont.) Q3: Retrieve the name of each employee who works on all the projects controlled by department number 5 Q3A: SELECT Fname, Lname FROM EMPLOYEE WHERE NOT EXISTS ( (SELECT Pnumber FROM PROJECT WHERE Dnum=5) EXCEPT (SELECT Pno FROM WORKS_ON WHERE Ssn=Essn)); Slide 3 - 15

16 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Joined Relations Feature in SQL2 Can specify a "joined relation" in the FROM- clause Looks like any other relation but is the result of a join Allows the user to specify different types of joins (regular "theta" JOIN, NATURAL JOIN, LEFT OUTER JOIN, RIGHT OUTER JOIN, FULL OUTER JOIN, CROSS JOIN, etc) Slide 3 - 16

17 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Joined Relations Feature in SQL2 (cont.) Q1:SELECTFNAME, LNAME, ADDRESS FROM EMPLOYEE, DEPARTMENT WHEREDNAME='Research' AND DNUMBER=DNO could be written as: Q1:SELECTFNAME, LNAME, ADDRESS FROM (EMPLOYEE JOIN DEPARTMENT ON DNUMBER=DNO) WHEREDNAME='Research’ or as: Q1:SELECTFNAME, LNAME, ADDRESS FROM (EMPLOYEE NATURAL JOIN DEPARTMENT AS DEPT(DNAME, DNO, MSSN, MSDATE) WHEREDNAME='Research’ Slide 3 - 17

18 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Joined Relations Feature in SQL2 (cont.) Q8:SELECTE.FNAME, E.LNAME, S.FNAME, S.LNAME FROM EMPLOYEE E S WHEREE.SUPERSSN=S.SSN can be written as: Q8:SELECTE.FNAME, E.LNAME, S.FNAME, S.LNAME FROM (EMPLOYEE E LEFT OUTER JOIN EMPLOYEES ON E.SUPERSSN=S.SSN) Slide 3 - 18

19 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Joined Relations Feature in SQL2 (cont.) Another Example; Q2: SELECT Pnumber, Dnum, Lname, Address, Bdate FROM PROJECT, DEPARTMENT, EMPLOYEE WHERE Dnum=Dnumber AND Mgr_ssn=Ssn AND Plocation=‘Stafford’; Q2: SELECT PNUMBER, DNUM, LNAME, BDATE, ADDRESS FROM (PROJECT JOIN DEPARTMENT ON DNUM=DNUMBER) JOIN EMPLOYEE ON MGRSSN=SSN) ) WHERE PLOCATION='Stafford ’ Slide 3 - 19

20 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition AGGREGATE FUNCTIONS Include COUNT, SUM, MAX, MIN, and AVG Query 15: Find the maximum salary, the minimum salary, and the average salary among all employees. Q15:SELECT MAX(SALARY), MIN(SALARY), AVG(SALARY) FROM EMPLOYEE –Some SQL implementations may not allow more than one function in the SELECT-clause Slide 3 - 20

21 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition AGGREGATE FUNCTIONS (cont.) Query 16: Find the maximum salary, the minimum salary, and the average salary among employees who work for the 'Research' department. Q16: SELECT MAX(SALARY), MIN(SALARY), AVG(SALARY) FROM EMPLOYEE, DEPARTMENT WHEREDNO=DNUMBER AND DNAME='Research' Slide 3 - 21

22 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition AGGREGATE FUNCTIONS (cont.) Queries 17 and 18: Retrieve the total number of employees in the company (Q17), and the number of employees in the 'Research' department (Q18). Q17:SELECT COUNT (*) FROM EMPLOYEE Q18:SELECT COUNT (*) FROM EMPLOYEE, DEPARTMENT WHEREDNO=DNUMBER AND DNAME='Research’ Slide 3 - 22

23 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition GROUPING In many cases, we want to apply the aggregate functions to subgroups of tuples in a relation Each subgroup of tuples consists of the set of tuples that have the same value for the grouping attribute(s) The function is applied to each subgroup independently SQL has a GROUP BY-clause for specifying the grouping attributes, which must also appear in the SELECT-clause Slide 3 - 23

24 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition GROUPING (cont.) Query 20: For each department, retrieve the department number, the number of employees in the department, and their average salary. Q20:SELECT DNO, COUNT (*), AVG (SALARY) FROM EMPLOYEE GROUP BYDNO –In Q20, the EMPLOYEE tuples are divided into groups--each group having the same value for the grouping attribute DNO –The COUNT and AVG functions are applied to each such group of tuples separately –The SELECT-clause includes only the grouping attribute and the functions to be applied on each group of tuples –A join condition can be used in conjunction with grouping Slide 3 - 24

25 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition GROUPING (cont.) Query 21: For each project, retrieve the project number, project name, and the number of employees who work on that project. Q21:SELECT PNUMBER, PNAME, COUNT (*) FROMPROJECT, WORKS_ON WHEREPNUMBER=PNO GROUP BYPNUMBER, PNAME –In this case, the grouping and functions are applied after the joining of the two relations Slide 3 - 25

26 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition THE HAVING-CLAUSE Sometimes we want to retrieve the values of these functions for only those groups that satisfy certain conditions The HAVING-clause is used for specifying a selection condition on groups (rather than on individual tuples) Slide 3 - 26

27 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition THE HAVING-CLAUSE (cont.) Query 22: For each project on which more than two employees work, retrieve the project number, project name, and the number of employees who work on that project. Q22: SELECT PNUMBER, PNAME, COUNT (*) FROMPROJECT, WORKS_ON WHEREPNUMBER=PNO GROUP BYPNUMBER, PNAME HAVINGCOUNT (*) > 2 Slide 3 - 27

28 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition ORDER BY The ORDER BY clause is used to sort the tuples in a query result based on the values of some attribute(s) in ascending or descending order Query 28: Retrieve a list of employees and the projects each works in, ordered by the employee's department, and within each department ordered alphabetically by employee last name. Q28: SELECT DNAME, LNAME, FNAME, PNAME FROM DEPARTMENT, EMPLOYEE, WORKS_ON, PROJECT WHEREDNUMBER=DNO AND SSN=ESSN ANDPNO=PNUMBER ORDER BYDNAME, LNAME [DESC|ASC] Slide 3 - 28

29 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Outline More Complex SQL Retrieval Queries Specifying Constraints as Assertions and Actions as Triggers Views in SQL Schema Change Statements in SQL Database Programming Slide 3 - 29

30 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Constraints as Assertions General constraints: constraints that do not fit in the basic SQL categories (presented in chapter 8) Mechanism: CREAT ASSERTION –components include: a constraint name, followed by CHECK, followed by a condition Slide 3 - 30

31 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Assertions: An Example “The salary of an employee must not be greater than the salary of the manager of the department that the employee works for’’ CREAT ASSERTION SALARY_CONSTRAINT CHECK (NOT EXISTS (SELECT * FROM EMPLOYEE E, EMPLOYEE M, DEPARTMENT D WHERE E.SALARY > M.SALARY AND E.DNO=D.NUMBER AND D.MGRSSN=M.SSN)) Slide 3 - 31

32 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition SQL Triggers Objective: to monitor a database and take action when a condition occurs Triggers are expressed in a syntax similar to assertions and include the following: –event (e.g., an update operation) –condition –action (to be taken when the condition is satisfied) Slide 3 - 32

33 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition SQL Triggers: An Example A trigger to compare an employee’s salary to his/her supervisor during insert or update operations: CREATE TRIGGER INFORM_SUPERVISOR BEFORE INSERT OR UPDATE OF SALARY, SUPERVISOR_SSN ON EMPLOYEE FOR EACH ROW WHEN (NEW.SALARY> (SELECT SALARY FROM EMPLOYEE WHERE SSN=NEW.SUPERVISOR_SSN)) INFORM_SUPERVISOR (NEW.SUPERVISOR_SSN,NEW.SSN; Slide 3 - 33

34 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Outline More Complex SQL Retrieval Queries Specifying Constraints as Assertions and Actions as Triggers Views in SQL Schema Change Statements in SQL Slide 3 - 34

35 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Views in SQL A view is a “virtual” table that is derived from other tables Allows for limited update operations (since the table may not physically be stored) Allows full query operations A convenience for expressing certain operations Slide 3 - 35

36 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Specification of Views SQL command: CREATE VIEW –a table (view) name –a possible list of attribute names (for example, when arithmetic operations are specified or when we want the names to be different from the attributes in the base relations) –a query to specify the table contents Slide 3 - 36

37 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition SQL Views: An Example Specify a different WORKS_ON table CREATE TABLE WORKS_ON_NEW AS SELECT FNAME, LNAME, PNAME, HOURS FROM EMPLOYEE, PROJECT, WORKS_ON WHERE SSN=ESSN AND PNO=PNUMBER GROUP BY PNAME; Slide 3 - 37

38 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Using a Virtual Table We can specify SQL queries on a newly create table (view): SELECT FNAME, LNAME FROM WORKS_ON_NEW WHERE PNAME=‘Seena’; When no longer needed, a view can be dropped: DROP WORKS_ON_NEW; Slide 3 - 38

39 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Efficient View Implementation Query modification: present the view query in terms of a query on the underlying base tables –disadvantage: inefficient for views defined via complex queries (especially if additional queries are to be applied to the view within a short time period) Slide 3 - 39

40 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Efficient View Implementation View materialization: involves physically creating and keeping a temporary table –assumption: other queries on the view will follow –concerns: maintaining correspondence between the base table and the view when the base table is updated –strategy: incremental update Slide 3 - 40

41 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition View Update Update on a single view without aggregate operations: update may map to an update on the underlying base table Views involving joins: an update may map to an update on the underlying base relations –not always possible Slide 3 - 41

42 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Un-updatable Views Views defined using groups and aggregate functions are not updateable Views defined on multiple tables using joins are generally not updateable WITH CHECK OPTION : must be added to the definition of a view if the view is to be updated –to allow check for updatability and to plan for an execution strategy Slide 3 - 42

43 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Outline More Complex SQL Retrieval Queries Specifying Constraints as Assertions and Actions as Triggers Views in SQL Schema Change Statements in SQL Slide 3 - 43

44 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition DROP Command Two drop behavior options: CASCADE & RESTRICT Examples: DROP SCHEMA COMPANY CASCADE; DROP TABLE DEPENDENT RESTRICT; Slide 3 - 44

45 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition ALTER TABLE Used to add an attribute to one of the base relations The new attribute will have NULLs in all the tuples of the relation right after the command is executed; hence, the NOT NULL constraint is not allowed for such an attribute Example: ALTER TABLE EMPLOYEE ADD JOB VARCHAR(12); ALTER TABLE COMPANY.EMPLOYEE DROP COLUMN Address CASCADE; ALTER TABLE COMPANY.DEPARTMENT ALTER COLUMN Mgr_ssn DROP DEFAULT; ALTER TABLE COMPANY.EMPLOYEE DROP CONSTRAINT EMPSUPERFK CASCADE; Slide 3 - 45

46 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Summary Slide 3 - 46

47 Copyright © 2004 Ramez Elmasri and Shamkant Navathe Elmasri/Navathe, Fundamentals of Database Systems, Fourth Edition Summary Slide 3 - 47


Download ppt "Chapter 3 MORE SQL Copyright © 2004 Pearson Education, Inc."

Similar presentations


Ads by Google