24

Sc - University of Waterloocs348/F07/lectures/sql-handout2.pdf · Employee Emgr where E.WorkDept = D.DeptNo and D.MgrNo = Emgr.EmpNo and E.Salary > Emgr.Salary List the last names

  • Upload
    others

  • View
    6

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Sc - University of Waterloocs348/F07/lectures/sql-handout2.pdf · Employee Emgr where E.WorkDept = D.DeptNo and D.MgrNo = Emgr.EmpNo and E.Salary > Emgr.Salary List the last names

An Introdu tion to Stru tured Query LanguageS hool of Computer S ien eUniversity of WaterlooCS 348Introdu tion to Database ManagementFall 2007CS 348 (Intro to Databases) SQL Fall 2007 1 / 48Outline1 The SQL Standard2 SQL DMLBasi QueriesData Modi� ationComplex QueriesSets vs. MultisetsUnknown valuesSubqueriesTable ExpressionsOuter joinsGrouping and AggregationHaving lausesOrdering results3 SQL DDLTablesIntegrity ConstraintsViewsTriggersCS 348 (Intro to Databases) SQL Fall 2007 2 / 48

Page 2: Sc - University of Waterloocs348/F07/lectures/sql-handout2.pdf · Employee Emgr where E.WorkDept = D.DeptNo and D.MgrNo = Emgr.EmpNo and E.Salary > Emgr.Salary List the last names

Stru tured Query LanguageStru tured Query Language (SQL) is made up of two sub-languages:� SQL Data Manipulation Language (DML)� SELECT statements perform queries� INSERT, UPDATE, DELETE statements modify the instan e of atable� SQL Data De�nition Language (DDL)� CREATE, DROP statements modify the database s hema� GRANT, REVOKE statements enfor e the se urity modelCS 348 (Intro to Databases) SQL Fall 2007 3 / 48The SQL StandardD

B

M

S

DATABASE

INTERNAL SCHEMA

CONCEPTUAL LEVEL

VIEW A VIEW B

APPLICATION 1 APPLICATION 2 APPLICATION 3

SQL

CS 348 (Intro to Databases) SQL Fall 2007 4 / 48

Page 3: Sc - University of Waterloocs348/F07/lectures/sql-handout2.pdf · Employee Emgr where E.WorkDept = D.DeptNo and D.MgrNo = Emgr.EmpNo and E.Salary > Emgr.Salary List the last names

SQL DML: Queriesselect LastName,HireDatefrom Employeewhere Salary > 100000

Find the last names and hiredates of employees who makemore than $100000.NoteSQL is de larative (non-navigational)CS 348 (Intro to Databases) SQL Fall 2007 5 / 48SQL Query Involving Several Relationsselect P.ProjNo, E.LastNamefrom Employee E, Project Pwhere P.RespEmp = E.EmpNo

and P.DeptNo = ’E21’

For ea h proje t for whi hdepartment E21 is respon-sible, �nd the name of theemployee in harge of thatproje t.CS 348 (Intro to Databases) SQL Fall 2007 6 / 48

Page 4: Sc - University of Waterloocs348/F07/lectures/sql-handout2.pdf · Employee Emgr where E.WorkDept = D.DeptNo and D.MgrNo = Emgr.EmpNo and E.Salary > Emgr.Salary List the last names

The SQL Basi Query Blo kselect attribute-expression-listfrom relation-list[where condition]NoteThe result of su h a query is a relation whi h has one attribute forea h element of the query's attribute-expression-list.CS 348 (Intro to Databases) SQL Fall 2007 7 / 48The SQL �Where� ClauseConditions may in lude� arithmeti operators +, -, *, /� omparisons =, <>, <, <=, >, >=� logi al onne tives and, or and not

select E.LastNamefrom Employee E,

Department D,Employee Emgr

where E.WorkDept = D.DeptNoand D.MgrNo = Emgr.EmpNoand E.Salary > Emgr.Salary

List the last names of em-ployees who make morethan their manager.CS 348 (Intro to Databases) SQL Fall 2007 8 / 48

Page 5: Sc - University of Waterloocs348/F07/lectures/sql-handout2.pdf · Employee Emgr where E.WorkDept = D.DeptNo and D.MgrNo = Emgr.EmpNo and E.Salary > Emgr.Salary List the last names

The SQL �Sele t� Clause� Return the di�eren e between ea h employee's a tual salary and abase salary of $40000select E.EmpNo, E.Salary - 40000 as SalaryDifffrom Employee E� As above, but report zero if the a tual salary is less than the basesalaryselect E.EmpNo,

case when E.Salary < 40000 then 0else E.Salary - 40000 end

from Employee ECS 348 (Intro to Databases) SQL Fall 2007 9 / 48SQL DML: Insertion & Deletioninsert into Employeevalues (’000350’,

’Sheldon’, ’Q’,’Jetstream’,’A00’,01/10/2000,25000.00);

Insert a single tuple into theEmployee relation.delete from Employee;

Delete all employees fromthe Employee table.delete from Employeewhere WorkDept = ’A00’;

Delete all employees in de-partment A00 from the Em-ployee table.CS 348 (Intro to Databases) SQL Fall 2007 10 / 48

Page 6: Sc - University of Waterloocs348/F07/lectures/sql-handout2.pdf · Employee Emgr where E.WorkDept = D.DeptNo and D.MgrNo = Emgr.EmpNo and E.Salary > Emgr.Salary List the last names

SQL DML: Updateupdate Employeeset Salary = Salary * 1.05;

In rease the salary of everyemployee by �ve per ent.update Employeeset WorkDept = ’E01’where WorkDept = ’E21’;

Move all employees in de-partment E21 into depart-ment E01.CS 348 (Intro to Databases) SQL Fall 2007 11 / 48Multisets� in the relational model, relations are sets� a ording to the SQL standard, tables are multisets (a.k.a. bags) -dupli ate tuples are allowed� SQL queries may result in dupli ates even if none of the inputtables themselves ontain dupli ates� Select distinct is used to eliminate dupli ates from theresult of a queryCS 348 (Intro to Databases) SQL Fall 2007 12 / 48

Page 7: Sc - University of Waterloocs348/F07/lectures/sql-handout2.pdf · Employee Emgr where E.WorkDept = D.DeptNo and D.MgrNo = Emgr.EmpNo and E.Salary > Emgr.Salary List the last names

Set Operations� SQL de�nes UNION,INTERSECT and EXCEPT operations (EXCEPTis set di�eren e)select empnofrom employeeexceptselect mgrnofrom department� These operations result in sets� Q1 UNION Q2 in ludes any tuple that is found (at least on e) in Q1or in Q2� Q1 INTERSECT Q2 in ludes any tuple that is found (at least on e)in both Q1 and Q2� Q1 EXCEPT Q2 in ludes any tuple that is found (at least on e) inQ1 and is not found Q2CS 348 (Intro to Databases) SQL Fall 2007 13 / 48Multiset Operations� SQL provides a multiset version of ea h of the set operations:UNION ALL, INTERSECT ALL, EXCEPT ALL� suppose Q1 in ludes n1 opies of some tuple t , and Q2 in ludes n2 opies of the same tuple t .� Q1 UNION ALL Q2 will in lude n1 + n2 opies of t� Q1 INTERSECT ALL Q2 will in lude min(n1;n2) opies of t� Q1 EXCEPT ALL Q2 will in lude max(n1 � n2; 0) opies of tCS 348 (Intro to Databases) SQL Fall 2007 14 / 48

Page 8: Sc - University of Waterloocs348/F07/lectures/sql-handout2.pdf · Employee Emgr where E.WorkDept = D.DeptNo and D.MgrNo = Emgr.EmpNo and E.Salary > Emgr.Salary List the last names

NULL values� the value NULL an be assigned to an attribute to indi ateunknown or missing data� NULLs are a ne essary evil - lots of NULLs in a database instan esuggests poor s hema design� NULLs an be prohibited for ertain attributes by s hema onstraints, e.g., NOT NULL, PRIMARY KEY� predi ates and expressions that involve attributes that may beNULL may evaluate to NULL� x + y evaluates to NULL if either x or y is NULL� x > y evaluates to NULL if either x or y is NULL� how to test for NULL? Use is NULL or is not NULLNoteSQL uses a three-valued logi : TRUE, FALSE, NULLCS 348 (Intro to Databases) SQL Fall 2007 15 / 48Logi al Expressions in SQLAND TRUE FALSE NULLTRUE TRUE FALSE NULLFALSE FALSE FALSE FALSENULL NULL FALSE NULLOR TRUE FALSE NULLTRUE TRUE TRUE TRUEFALSE TRUE FALSE NULLNULL TRUE NULL NULLNOT TRUE FALSE NULLFALSE TRUE NULLCS 348 (Intro to Databases) SQL Fall 2007 16 / 48

Page 9: Sc - University of Waterloocs348/F07/lectures/sql-handout2.pdf · Employee Emgr where E.WorkDept = D.DeptNo and D.MgrNo = Emgr.EmpNo and E.Salary > Emgr.Salary List the last names

NULL and the SQL Where Clause� The query:select *from employeewhere hiredate <> ’05/05/1947’will not return information about employees whose hiredate isNULL.NoteThe ondition in a where lause �lters out any tuples for whi hthe ondition evaluates to FALSE or to NULL.CS 348 (Intro to Databases) SQL Fall 2007 17 / 48Subqueries� These two queries are equivalent.select deptno, deptnamefrom department d, employee ewhere d.mgrno = e.empno and e.salary > 50000

select deptno, deptnamefrom departmentwhere mgrno in

( select empnofrom employeewhere salary > 50000 )CS 348 (Intro to Databases) SQL Fall 2007 18 / 48

Page 10: Sc - University of Waterloocs348/F07/lectures/sql-handout2.pdf · Employee Emgr where E.WorkDept = D.DeptNo and D.MgrNo = Emgr.EmpNo and E.Salary > Emgr.Salary List the last names

Subquery Constru ts in SQL� SQL supports the use of the following predi ates in thewhere lause. A is an attribute, Q is a query, op is one of>;<;<>;=; <=; >=.� A IN (Q)� A NOT IN (Q)� A op SOME (Q)� A op ALL (Q)� EXISTS (Q)� NOT EXISTS (Q)� For the �rst four forms, the result of Q must have a singleattribute.CS 348 (Intro to Databases) SQL Fall 2007 19 / 48Another Subquery Example� Find the name(s) and number(s) of the employee(s) with thehighest salary.select empno, lastnamefrom employeewhere salary >= all

( select salaryfrom employee )NoteIs this query orre t if the s hema allows the salary attribute to ontain NULLs?CS 348 (Intro to Databases) SQL Fall 2007 20 / 48

Page 11: Sc - University of Waterloocs348/F07/lectures/sql-handout2.pdf · Employee Emgr where E.WorkDept = D.DeptNo and D.MgrNo = Emgr.EmpNo and E.Salary > Emgr.Salary List the last names

Correlated Subqueries� This query also returns the employee(s) with the largest salary:select empno, lastnamefrom employee E1where salary is not null and not exists

( select *from employee E2where E2.salary > E1.salary)� This query ontains a orrelated subquery - the subquery refers toan attribute (E1.salary) from the outer query.CS 348 (Intro to Databases) SQL Fall 2007 21 / 48S alar Subqueries� in the where lause:

select empno, lastnamefrom employeewhere salary >

(select salaryfrom employee e2where e2.empno = ’000190’)� in the sele t lause:

select projno,(select deptnamefrom department dwhere e.workdept = d.deptno)

from project p, employee ewhere p.respemp = e.empnoCS 348 (Intro to Databases) SQL Fall 2007 22 / 48

Page 12: Sc - University of Waterloocs348/F07/lectures/sql-handout2.pdf · Employee Emgr where E.WorkDept = D.DeptNo and D.MgrNo = Emgr.EmpNo and E.Salary > Emgr.Salary List the last names

Table Expressions� in the from lause:select projno, projnamefrom project p,

(select mgrnofrom department, employeewhere mgrno = empno and salary > 100000) as m

where respemp = mgrno� in a with lause:with Mgrs(empno) as

(select mgrnofrom department, employeewhere mgrno = empno and salary > 100000)

select projno, projnamefrom project, Mgrswhere respemp = empnoCS 348 (Intro to Databases) SQL Fall 2007 23 / 48Outer Joins� List the manager of ea h department. In lude in the resultdepartments that have no manager.select deptno, deptname, lastnamefrom department d left outer join employee e

on d.mgrno = e.empnowhere deptno like ’D%’NoteSQL supports left, right, and full outer joins.CS 348 (Intro to Databases) SQL Fall 2007 24 / 48

Page 13: Sc - University of Waterloocs348/F07/lectures/sql-handout2.pdf · Employee Emgr where E.WorkDept = D.DeptNo and D.MgrNo = Emgr.EmpNo and E.Salary > Emgr.Salary List the last names

Grouping and Aggregation: An Example� For ea h department, list the number of employees it has and their ombined salary.select deptno, deptname, sum(salary) as totalsalary,

count(*) as employeesfrom department d, employee ewhere e.workdept = d.deptnogroup by deptno, deptnameCS 348 (Intro to Databases) SQL Fall 2007 25 / 48Grouping and Aggregation: Operational Semanti s� The result of a query involving grouping and aggregation an bedetermined as follows:1 form the ross produ t of the relations in the from lause2 eliminate tuples that do not satisy the ondition in thewhere lause3 form the remaining tuples into groups, where all of the tuples in agroup mat h on all of the grouping attributes4 eliminate any groups of tuples for whi h the having lause is notsatis�ed5 generate one tuple per group. Ea h tuple has one attribute perexpression in the sele t lause.� aggregation fun tions are evaluated separately for ea h groupCS 348 (Intro to Databases) SQL Fall 2007 26 / 48

Page 14: Sc - University of Waterloocs348/F07/lectures/sql-handout2.pdf · Employee Emgr where E.WorkDept = D.DeptNo and D.MgrNo = Emgr.EmpNo and E.Salary > Emgr.Salary List the last names

Grouping and Aggregation ExampleDEPTNO DEPTNAME SALARY------ ----------------------------- -----------A00 SPIFFY COMPUTER SERVICE DIV. 52750.00A00 SPIFFY COMPUTER SERVICE DIV. 46500.00B01 PLANNING 41250.00C01 INFORMATION CENTER 38250.00D21 ADMINISTRATION SYSTEMS 36170.00D21 ADMINISTRATION SYSTEMS 22180.00D21 ADMINISTRATION SYSTEMS 19180.00D21 ADMINISTRATION SYSTEMS 17250.00D21 ADMINISTRATION SYSTEMS 27380.00E01 SUPPORT SERVICES 40175.00E11 OPERATIONS 29750.00E11 OPERATIONS 26250.00E11 OPERATIONS 17750.00E11 OPERATIONS 15900.00E21 SOFTWARE SUPPORT 26150.00CS 348 (Intro to Databases) SQL Fall 2007 27 / 48Grouping and Aggregation Example ( ont'd)DEPTNO DEPTNAME SALARY------ ----------------------------- -----------A00 SPIFFY COMPUTER SERVICE DIV. 52750.00A00 SPIFFY COMPUTER SERVICE DIV. 46500.00B01 PLANNING 41250.00C01 INFORMATION CENTER 38250.00D21 ADMINISTRATION SYSTEMS 36170.00D21 ADMINISTRATION SYSTEMS 22180.00D21 ADMINISTRATION SYSTEMS 19180.00D21 ADMINISTRATION SYSTEMS 17250.00D21 ADMINISTRATION SYSTEMS 27380.00E01 SUPPORT SERVICES 40175.00E11 OPERATIONS 29750.00E11 OPERATIONS 26250.00E11 OPERATIONS 17750.00E11 OPERATIONS 15900.00E21 SOFTWARE SUPPORT 26150.00CS 348 (Intro to Databases) SQL Fall 2007 28 / 48

Page 15: Sc - University of Waterloocs348/F07/lectures/sql-handout2.pdf · Employee Emgr where E.WorkDept = D.DeptNo and D.MgrNo = Emgr.EmpNo and E.Salary > Emgr.Salary List the last names

Grouping and Aggregation Example ( ont'd)DEPTNO DEPTNAME TOTALSALARY EMPLOYEES------ ----------------------------- ----------- ---------A00 SPIFFY COMPUTER SERVICE DIV. 99250.00 2B01 PLANNING 41250.00 1C01 INFORMATION CENTER 38250.00 1D21 ADMINISTRATION SYSTEMS 122160.00 5E01 SUPPORT SERVICES 40175.00 1E11 OPERATIONS 89650.00 4E21 SOFTWARE SUPPORT 26150.00 1CS 348 (Intro to Databases) SQL Fall 2007 29 / 48Aggregation Fun tions in SQL� ount(*): number of tuples in the group� ount(E): number of tuples for whi h E (an expression that mayinvolve non-grouping attributes) is non-NULL� ount(distin t E): number of distin t non-NULL E values� sum(E): sum of non-NULL E values� sum(distin t E): sum of distin t non-NULL E values� avg(E): average of non-NULL E values� avg(distin t E): average of distin t non-NULL E values� min(E): minimum of non-NULL E values� max(E): maximum of non-NULL E valuesCS 348 (Intro to Databases) SQL Fall 2007 30 / 48

Page 16: Sc - University of Waterloocs348/F07/lectures/sql-handout2.pdf · Employee Emgr where E.WorkDept = D.DeptNo and D.MgrNo = Emgr.EmpNo and E.Salary > Emgr.Salary List the last names

Sele ting Non-Grouping Attributesdb2 => select deptno, deptname, count(*), sum(salary) \db2 (cont.) => from department d, employee e \db2 (cont.) => where e.workdept = d.deptno \db2 (cont.) => group by deptnoSQL0119N An expression starting with "DEPTNAME"specified in a SELECT clause, HAVING clause, orORDER BY clause is not specified in the GROUP BY clauseor it is in a SELECT clause, HAVING clause, or ORDER BYclause with a column function and no GROUP BY clause isspecified. SQLSTATE=42803NoteNon-grouping attributes may appear in the sele t lause only inaggregate expressions. (Why?)CS 348 (Intro to Databases) SQL Fall 2007 31 / 48The Having Clause� List the average salary for ea h large department.

select deptno, deptname, avg(salary) as MeanSalaryfrom department d, employee ewhere e.workdept = d.deptnogroup by deptno, deptnamehaving count(*) >= 4NoteThe where lause �lters tuples before they are grouped, thehaving lause �lters groups.CS 348 (Intro to Databases) SQL Fall 2007 32 / 48

Page 17: Sc - University of Waterloocs348/F07/lectures/sql-handout2.pdf · Employee Emgr where E.WorkDept = D.DeptNo and D.MgrNo = Emgr.EmpNo and E.Salary > Emgr.Salary List the last names

Grouping and Aggregation with HavingDEPTNO DEPTNAME SALARY------ ----------------------------- -----------A00 SPIFFY COMPUTER SERVICE DIV. 52750.00A00 SPIFFY COMPUTER SERVICE DIV. 46500.00B01 PLANNING 41250.00C01 INFORMATION CENTER 38250.00D21 ADMINISTRATION SYSTEMS 36170.00D21 ADMINISTRATION SYSTEMS 22180.00D21 ADMINISTRATION SYSTEMS 19180.00D21 ADMINISTRATION SYSTEMS 17250.00D21 ADMINISTRATION SYSTEMS 27380.00E01 SUPPORT SERVICES 40175.00E21 SOFTWARE SUPPORT 26150.00E11 OPERATIONS 29750.00E11 OPERATIONS 26250.00E11 OPERATIONS 17750.00E11 OPERATIONS 15900.00CS 348 (Intro to Databases) SQL Fall 2007 33 / 48Grouping and Aggregation with Having ( ont'd)DEPTNO DEPTNAME SALARY------ ----------------------------- -----------D21 ADMINISTRATION SYSTEMS 36170.00D21 ADMINISTRATION SYSTEMS 22180.00D21 ADMINISTRATION SYSTEMS 19180.00D21 ADMINISTRATION SYSTEMS 17250.00D21 ADMINISTRATION SYSTEMS 27380.00E11 OPERATIONS 29750.00E11 OPERATIONS 26250.00E11 OPERATIONS 17750.00E11 OPERATIONS 15900.00CS 348 (Intro to Databases) SQL Fall 2007 34 / 48

Page 18: Sc - University of Waterloocs348/F07/lectures/sql-handout2.pdf · Employee Emgr where E.WorkDept = D.DeptNo and D.MgrNo = Emgr.EmpNo and E.Salary > Emgr.Salary List the last names

Grouping and Aggregation with Having ( ont'd)DEPTNO DEPTNAME MEANSALARY------ ----------------------------- -----------D21 ADMINISTRATION SYSTEMS 24432.00E11 OPERATIONS 22412.50

CS 348 (Intro to Databases) SQL Fall 2007 35 / 48Ordering Results� No parti ular ordering on the rows of a table an be assumedwhen queries are written. (This is important!)� No parti ular ordering of rows of an intermediate result in thequery an be assumed either.� However, it is possible to order the �nal result of a query, usingthe order by lause.select distinct e.empno, emstdate, firstnme, lastnamefrom employee e, emp_act awhere e.empno = a.empno and a.projno = ’PL2100’order by emstdateCS 348 (Intro to Databases) SQL Fall 2007 36 / 48

Page 19: Sc - University of Waterloocs348/F07/lectures/sql-handout2.pdf · Employee Emgr where E.WorkDept = D.DeptNo and D.MgrNo = Emgr.EmpNo and E.Salary > Emgr.Salary List the last names

SQL DDL: Tablescreate table Employee (

EmpNo char(6),FirstName varchar(12),MidInit char(1),LastName varchar(15),WorkDept char(3),HireDate date

);

alter table Employeeadd column Salary decimal(9,2);

drop table Employee;CS 348 (Intro to Databases) SQL Fall 2007 37 / 48SQL DDL: Data TypesSome of the attribute domains de�ned in SQL:� INTEGER� DECIMAL(p,q): p-bit numbers, with q bits right of de imal� FLOAT(p): p-bit �oating point numbers� CHAR(n): �xed length hara ter string, length n� VARCHAR(n): variable length hara ter string, max. length n� DATE: des ribes a year, month, day� TIME: des ribes an hour, minute, se ond� TIMESTAMP: des ribes and date and a time on that date� YEAR/MONTH INTERVAL: time interval� DAY/TIME INTERVAL: time interval� : : :CS 348 (Intro to Databases) SQL Fall 2007 38 / 48

Page 20: Sc - University of Waterloocs348/F07/lectures/sql-handout2.pdf · Employee Emgr where E.WorkDept = D.DeptNo and D.MgrNo = Emgr.EmpNo and E.Salary > Emgr.Salary List the last names

Integrity Constraints in SQLMost ommonly-used SQL s hema onstraints:� Not Null� Primary Key� Unique� Foreign Key� Column or Tuple Che kNoteRe ent SQL standards also allows more powerful integrity onstraints. However, they are not supported by all ommer ialDBMSs.CS 348 (Intro to Databases) SQL Fall 2007 39 / 48SQL DDL: Integrity Constraintscreate table Employee (

EmpNo char(6) not null primary key,FirstName varchar(12) not null,MidInit char(1),LastName varchar(15) not null,WorkDept char(3) not null references Department

on delete cascade,HireDate date,Salary decimal(9,2) check (Salary >= 10000),constraint unique_name_in_deptunique (FirstName, LastName, WorkDept)

);

alter table Employeeadd column StartDate date,constraint hire_before_startcheck (HireDate <= StartDate);CS 348 (Intro to Databases) SQL Fall 2007 40 / 48

Page 21: Sc - University of Waterloocs348/F07/lectures/sql-handout2.pdf · Employee Emgr where E.WorkDept = D.DeptNo and D.MgrNo = Emgr.EmpNo and E.Salary > Emgr.Salary List the last names

Another SQL Constraint Examplecreate table registeredin (

coursenum char(5) not null,term char(3) not null,id char(8) not null references student

on delete no action,sectionnum char(2) not null,mark integer,constraint mark_check check (( mark >= 0 and mark <= 100 ) or mark is null

),primary key (coursenum, term, id),foreign key (coursenum, sectionnum, term)references section

)CS 348 (Intro to Databases) SQL Fall 2007 41 / 48More Powerful SQL Integrity Constraintscreate assertion balanced_budget check (not exists (

select deptnofrom department dwhere budget <

(select sum(salary)from employeewhere workdept = d.deptno)))NoteGeneral assertions are not supported by urrent versions of DB2.CS 348 (Intro to Databases) SQL Fall 2007 42 / 48

Page 22: Sc - University of Waterloocs348/F07/lectures/sql-handout2.pdf · Employee Emgr where E.WorkDept = D.DeptNo and D.MgrNo = Emgr.EmpNo and E.Salary > Emgr.Salary List the last names

ViewsRe all the three-level s hema ar hite ture:1 External s hema2 Con eptual s hema3 Physi al s hemaDe�nition (View)A view is a relation in the external s hema whose instan e isdetermined by the instan es of the relations in the on eptual s hema.A view has many of the same properties as a base relation in the on eptual s hema:� its s hema information appears in the database s hema� a ess ontrols an be applied to it� other views an be de�ned in terms of itCS 348 (Intro to Databases) SQL Fall 2007 43 / 48Updating Views� Modi� ations to a view's instan e must be propagated ba k toinstan es of relations in on eptual s hema.� Some views annot be updated unambiguously.Con eptual S hemaPersonsNAME CITIZENSHIPEd CanadianDave CanadianWes Ameri anNationalPastimesCITIZENSHIP PASTIMECanadian Ho keyCanadian CurlingAmeri an Ho keyAmeri an Baseball , External S hemaPersonalPastimesNAME PASTIMEEd Ho keyEd CurlingDave Ho keyDave CurlingWes Ho keyWes Baseball1 What does it mean to insert (Darryl, Ho key)?2 What does it mean to delete (Dave, Curling)?CS 348 (Intro to Databases) SQL Fall 2007 44 / 48

Page 23: Sc - University of Waterloocs348/F07/lectures/sql-handout2.pdf · Employee Emgr where E.WorkDept = D.DeptNo and D.MgrNo = Emgr.EmpNo and E.Salary > Emgr.Salary List the last names

SQL DDL: ViewsCustomizing the s hema for a parti ular user/appli ation:create view ManufacturingProjects as

( select projno, projname, firstnme, lastnamefrom project, employeewhere respemp = empno and deptno = ’D21’ )On e de�ned, SQL DML an be used to query a view like any othertable:

select * from ManufacturingProjectsCS 348 (Intro to Databases) SQL Fall 2007 45 / 48View Updates in SQLA ording to SQL-92, a view is updatable only if its de�nition satis�esa variety of onditions:� The query referen es exa tly one table� The query only outputs simple attributes (no expressions)� There is no grouping/aggregation/distin t� There are no nested queries� There are no set operationsThese rules are more restri tive than ne essary.CS 348 (Intro to Databases) SQL Fall 2007 46 / 48

Page 24: Sc - University of Waterloocs348/F07/lectures/sql-handout2.pdf · Employee Emgr where E.WorkDept = D.DeptNo and D.MgrNo = Emgr.EmpNo and E.Salary > Emgr.Salary List the last names

TriggersDe�nitionA trigger is a pro edure exe uted by the database in response to a hange to the database instan e.Basi omponents of a trigger des ription:Event: Type of hange that should ause trigger to �reCondition: Test performed by trigger to determine whether furthera tion is neededA tion: Pro edure exe uted if ondition is metCS 348 (Intro to Databases) SQL Fall 2007 47 / 48SQL DDL: Trigger Examplecreate trigger log_addr

after update of addr, phone on personreferencing OLD as o NEW as nfor each rowmode DB2SQL /* DB2-specific syntax */when (o.status = ’VIP’ or n.status = ’VIP’)

insert into VIPaddrhist(pid, oldaddr, oldphone,newaddr, newphone, user, modtime)

values (o.pid, o.addr, o.phone,n.addr, n.phone, user, current timestamp);CS 348 (Intro to Databases) SQL Fall 2007 48 / 48