Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen 2002-2008 Views These slides are licensed under.

Similar presentations


Presentation on theme: "1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen 2002-2008 Views These slides are licensed under."— Presentation transcript:

1 1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen 2002-2008 Views These slides are licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License. For more information on how you may use them, please see http://www.openlineconsult.com/db

2 2 © Ellis Cohen 2001-2008 Overview of Lecture Introduction to Views View-Based Problem Solving Views and Inspectability Table Expressions, Inline Views & Factoring Using Views with Grouping Views and Outer Joins State Assertions Using Manifest Views Complex State Assertions View-Based Modification Materialized Views

3 3 © Ellis Cohen 2001-2008 Introduction to Views

4 4 © Ellis Cohen 2001-2008 Views: Virtual Tables Views allow you to –Name a query –Treat it like a table (it's not, though) –Every time the view is used in a query, the view's description is used Use views for –Convenience –Security –Separating Complex Queries

5 5 © Ellis Cohen 2001-2008 Creating Tables vs. Views CREATE VIEW HiEmps AS SELECT * FROM Emps WHERE sal > 1500 Creates a new table. Subsequent changes to Emps will not be reflected in HiEmps. Just creates a view based on Emps. Every use of HiEmps actually refers to its underlying base tables – in this case, Emps. CREATE TABLE HiEmps AS SELECT * FROM Emps WHERE sal > 1500

6 6 © Ellis Cohen 2001-2008 View Expansion Suppose we define CREATE VIEW HiEmps AS SELECT * FROM Emps WHERE sal > 1500 and then execute the query SELECT ename, job FROM HiEmps The database engine automatically expands this into SELECT ename, job FROM Emps WHERE sal > 1500

7 7 © Ellis Cohen 2001-2008 What is a View A view is not a table A view does not hold data A view just names a description used in expanding queries which refer to the view! A view name can be used in a query anyplace a table name can be used

8 8 © Ellis Cohen 2001-2008 Views Provide Security CREATE VIEW JustSales AS SELECT empno, ename FROM Emps WHERE job = 'SALESMAN' Grant a user access to JustSales, but not to Emps That user can then obtain current information only about the empno and the ename of sales persons. When using a view in a query, only the attributes projected by the view can be accessed

9 9 © Ellis Cohen 2001-2008 Views Simplify User Queries Goal: provide a user with a single relation consisting of employee & department information of employees with high salaries. Instead of having to write SELECT ename, dname FROM (Emps NATURAL JOIN Depts) WHERE sal > 1500 the user can can simply write (and even be unaware of the salary threshold of 1500) SELECT ename, dname FROM EmpDeptView if we just define the view: CREATE VIEW EmpDeptView AS SELECT * FROM (Emps NATURAL JOIN Depts) WHERE sal > 1500 This view is permanently created; so it must be explicitly dropped

10 10 © Ellis Cohen 2001-2008 Dynamic Views The result of querying a view may change even if the data in their underlying tables stays the same. Suppose Emps contains two attributes: startVacation & endVacation, with the dates of an employee's next currently scheduled vacation The view OnVacation indicates which employees are currently on vacation CREATE VIEW OnVacation AS SELECT empno, ename FROM Emps WHERE getdate() BETWEEN startVacation AND endVacation How might the view change as the date changes?

11 11 © Ellis Cohen 2001-2008 View-Based Problem Solving

12 12 © Ellis Cohen 2001-2008 Divide & Conquer Views are a problem solving tool. To write a complex query to solve a problem, identify a view such that a)If the view were already defined, you could see how to use it to solve the problem b)It is easier to figure out how to write the SQL for the view than the SQL to solve the original problem.

13 13 © Ellis Cohen 2001-2008 Problem Solving Example Problem: Get the average salary of non-clerks in each of the departments located in New York Identify a View: NyNonClerks The employee & dept information for all non-clerks whose department is located in NY Use the View to Solve the Problem: Get the average salary of the employees in each department in NyNonClerks

14 14 © Ellis Cohen 2001-2008 SQL for Example Problem: Get the average salary of non-clerks in each of the departments located in New York Identify a View: NyNonClerks CREATE VIEW NyNonClerks AS SELECT * FROM (Emps NATURAL JOIN Depts) WHERE (job <> 'CLERK') AND (loc = 'New York') Use the View to Solve the Problem: SELECT dname, avg(sal) as avgsal FROM NyNonClerks GROUP BY dname

15 15 © Ellis Cohen 2001-2008 View Expansion CREATE VIEW NyNonClerks AS SELECT * FROM (Emps NATURAL JOIN Depts) WHERE (job <> 'CLERK') AND (loc = 'New York') SELECT dname, avg(sal) as avgsal FROM NyNonClerks GROUP BY dname SELECT dname, avg(sal) as avgsal FROM (Emps NATURAL JOIN Depts) WHERE (job <> 'CLERK') AND (loc = 'New York') GROUP BY dname

16 16 © Ellis Cohen 2001-2008 View Exercise Problem: List the project name and the project manager's name of all projects managed by department managers (i.e. whose job is DEPTMGR) 1)Identify a view that will simplify this problem 2)Write the SQL to solve the problem using the view 3)Write the SQL to create the view Identify the view

17 17 © Ellis Cohen 2001-2008 Possible Views Problem: List the project name and the project manager's name of all projects managed by department managers (i.e. whose job is DEPTMGR) Possible Views DeptMgrs: All employee info about employees whose job is DEPTMGR ProjMgrs: For each project, all information about the project and about the employee who manages it. For either of these possible views write the SQL to solve the problem using the view write the SQL to create the view

18 18 © Ellis Cohen 2001-2008 View Exercise Answer CREATE VIEW ProjMgrs AS SELECT * FROM (Projs p JOIN Emps e ON p.pmgr = e.empno) SELECT pname, ename FROM ProjMgrs WHERE job = 'DEPTMGR' CREATE VIEW DeptMgrs AS SELECT * FROM Emps WHERE job = 'DEPTMGR' SELECT pname, ename FROM (Projs p JOIN DeptMgrs m ON p.pmgr = m.empno) A view name can be used in a query anyplace a table name can be used

19 19 © Ellis Cohen 2001-2008 Views and Inspectability

20 20 © Ellis Cohen 2001-2008 Inspectable Queries & Views A query or view is inspectable if you can easily tell if it is defined correctly by comparing –the contents of the query or view, and –the contents of the tables and other views it uses in its definitions A query of view that is not inspectable is too complex, and too hard to debug and maintain

21 21 © Ellis Cohen 2001-2008 A Complex Problem's Join Diagram Projs p pno pname pmgr persons budget pstart pend Emps e empno ename job mgr hiredate sal comm deptno Emps m empno ename job mgr hiredate sal comm deptno Asns a pno empno Emps ae empno ename job mgr hiredate sal comm deptno NULL is not For each budgeted project managed by a direct manager, list the project name, the manager's name, and the names of the other employees (if any) assigned to the project. [Assume all projects have a project manager]

22 22 © Ellis Cohen 2001-2008 A Non-Inspectable Query SELECT DISTINCT p.pname, m.ename, ae.ename FROM (Emps m JOIN Emps e ON m.empno = e.mgr), (Projs p NATURAL LEFT JOIN (Asns a NATURAL JOIN Emps ae)), WHERE m.empno = p.pmgr AND p.budget IS NOT NULL For each budgeted project managed by a direct manager, list the project name, the manager's name, and the names of the other employees (if any) assigned to the project. [Assume all projects have a project manager]

23 23 © Ellis Cohen 2001-2008 Divide & Conquer If a query or view is not inspectable (i.e. it is too complex for the context in which it will be used): Define one or more intermediate views, so that –The query or view is now inspectable when it is rewritten using the intermediate view(s)

24 24 © Ellis Cohen 2001-2008 Dividing Complex Problem Projs p pno pname pmgr persons budget pstart pend Emps e empno ename job mgr hiredate sal comm deptno Emps m empno ename job mgr hiredate sal comm deptno Asns a pno empno Emps empno ename job mgr hiredate sal comm deptno NULL is not DirectMgrs BudgetedProjectMembers Direct Managers empno ename Budgeted Project Members pname pmgr ename Divide & Conquer based on two views which are inspectable

25 25 © Ellis Cohen 2001-2008 Inspectable Queries and Views CREATE VIEW DirectMgrs AS SELECT DISTINCT m.empno, m.ename FROM (Emps m JOIN Emps e ON m.empno = e.mgr) CREATE VIEW BudgetedProjectMembers AS SELECT b.pname, b.pmgr, ae.ename FROM (BudgetedProjects b NATURAL LEFT JOIN (Asns a NATURAL JOIN Emps e)) WHERE p.budget IS NOT NULL SELECT b.pname, m.ename, b.ename FROM (DirectMgrs m JOIN BudgetedProjectMembers b ON m.empno = b.pmgr)

26 26 © Ellis Cohen 2001-2008 Debugging & Inspectability If your view seems to have values that are incorrect, how do you know if –the view has been defined incorrectly –the underlying tables have incorrect values A sequence of inspectable views lets you check both definitions and values at each step of the way

27 27 © Ellis Cohen 2001-2008 Table Expressions, Inline Views & Factoring

28 28 © Ellis Cohen 2001-2008 Table Expressions as Inline Views SELECT pname, ename FROM Projs p, (SELECT * FROM Emps WHERE job = 'DEPTMGR') m WHERE p.pmgr = m.empno CREATE VIEW DeptMgrs AS SELECT * FROM Emps WHERE job = 'DEPTMGR' SELECT pname, ename FROM Projs p, DeptMgrs m WHERE p.pmgr = m.empno Created views are permanently created and must be explicitly dropped Inline views are not named and not permanently created. They are UGLY though! Instead of using the view name, include its definition (called a table expression)

29 29 © Ellis Cohen 2001-2008 Factoring WITH DeptMgrs AS (SELECT * FROM Emps WHERE job = 'DEPTMGR') SELECT pname, ename FROM (Projs p JOIN DeptMgrs m ON p.pmgr = m.empno) Factoring allows the definition of named views without permanent view creation Oracle 9i up only Defines named views ONLY for the life of the query The WITH clause of the SELECT statement can define one or more factored views (separated by commas) Each can refer to any factored views defined above it

30 30 © Ellis Cohen 2001-2008 Using Views When use views? When necessary, or to make SQL easier to understand and maintain. When use inline views? Almost NEVER! When use created views? When you expect to reuse the view in more than a single query When the view is used for security or information hiding For debugging & maintenance When use factored views? When you want to use a view to simplify your SQL, but you don't have any reason to use a created view

31 31 © Ellis Cohen 2001-2008 Using Views with Grouping

32 32 © Ellis Cohen 2001-2008 Divide & Conquer Problem Suppose I want to know How many departments have 3 or more employees? What view would be useful in order to answer this question? deptno ?

33 33 © Ellis Cohen 2001-2008 Divide & Conquer View deptno knt 106 202 304 400 Do I need to know about departments that don't have employees? Given the DeptKnts view: What's the code needed to answer: How many departments have 3 or more employees? DeptKnts

34 34 © Ellis Cohen 2001-2008 Query Based on View deptno knt 106 202 304 400 How many departments have 3 or more employees? DeptKnts SELECT count(*) FROM DeptKnts WHERE knt >= 3 Rewrite the query, with DeptKnts defined using a factored view (no need to include result tuples for depts without employees)

35 35 © Ellis Cohen 2001-2008 Divide & Conquer Code WITH DeptKnts AS ( SELECT deptno, count(*) AS knt FROM Emps GROUP BY deptno ) SELECT count(*) FROM DeptKnts WHERE knt >= 3

36 36 © Ellis Cohen 2001-2008 Views with Grouping & Joins List the names of employees whose salary is less than the average salary for their job empno ename sal job 7499ALLEN1600SALESMAN 7654MARTIN1250SALESMAN 7698BLAKE2850DEPTMGR 7839KING5000PRESIDENT 7844TURNER1500SALESMAN 7986STERN1500ENGINEER Emps ? Can you imagine having some other table. If you could join it with Emps, you could very easily write SQL to solve this problem

37 37 © Ellis Cohen 2001-2008 Views with Grouping List the employees whose salary is less than the average salary for their job empno ename sal job … 7499ALLEN1600SALESMAN 7654MARTIN1250SALESMAN 7698BLAKE2850DEPTMGR 7839KING5000PRESIDENT 7844TURNER1500SALESMAN 7986STERN1500ENGINEER Emps AvgJobSals job avgsal SALESMAN1450 DEPTMGR2850 PRESIDENT5000 ENGINEER1500 SELECT ename FROM Emps NATURAL JOIN AvgJobSals WHERE sal < avgsal Rewrite, defining AvgJobSals as a factored view

38 38 © Ellis Cohen 2001-2008 Factored View with Grouping WITH AvgJobSals AS (SELECT job, avg(sal) AS avgsal FROM Emps GROUP BY job) SELECT ename FROM (Emps NATURAL JOIN AvgJobSals) WHERE sal < avgsal

39 39 © Ellis Cohen 2001-2008 Group Restriction Exercise Find a way to write (in SQL) SELECT job, avg(sal) AS avgsal FROM Emps GROUP BY job HAVING count(DISTINCT deptno) > 1 Find the average salary for any job where employees in more than one department have that job without using HAVING, by using Factored Views Rewrite without using HAVING, joins, or subqueries!

40 40 © Ellis Cohen 2001-2008 Group Restriction Using Views ANALYST12500 CLERK21900 DEPTMGR32000 job dknt avgsal empno job deptno sal 7839ANALYST102000 7838ANALYST103000 7499CLERK301600 7654CLERK301250 7698CLERK502850 7844DEPTMGR101500 7986DEPTMGR301500 7219DEPTMGR503000 Emps CLERK1900 DEPTMGR2000 job avgsal SELECT job, avg(sal) AS avgsal FROM Emps GROUP BY job HAVING count(DISTINCT deptno) > 1 Define a view JobInfo which corresponds to the table below

41 41 © Ellis Cohen 2001-2008 Using and Defining Views ANALYST12500 CLERK21900 DEPTMGR32000 job dknt avgsal empno job deptno sal 7839ANALYST102000 7838ANALYST103000 7499CLERK301600 7654CLERK301250 7698CLERK502850 7844DEPTMGR101500 7986DEPTMGR301500 7219DEPTMGR503000 Emps CLERK1900 DEPTMGR2000 job avgsal SELECT job, avgsal FROM JobInfo WHERE dknt > 1 CREATE VIEW JobInfo AS SELECT job, avg(sal) AS avgsal, count(DISTINCT deptno) AS dknt FROM Emps GROUP BY job JobInfo

42 42 © Ellis Cohen 2001-2008 Factored View Answer WITH JobInfo AS (SELECT job, avg(sal) AS avgsal, count(DISTINCT deptno) AS dknt FROM Emps GROUP BY job) SELECT job, avgsal FROM JobInfo WHERE dknt > 1

43 43 © Ellis Cohen 2001-2008 Views and Outer Joins

44 44 © Ellis Cohen 2001-2008 Example Without a View List the # of clerks in every department (including those with none) SELECT deptno, count(empno) AS knt FROM (Depts d LEFT JOIN Emps e ON e.deptno = d.deptno AND job = 'CLERK')) GROUP by deptno Rewrite this using a view

45 45 © Ellis Cohen 2001-2008 Factored Left Join Example List the # of clerks in every department (including those with none) WITH Clerks AS (SELECT * FROM Emps WHERE job = 'CLERK') SELECT deptno, count(empno) AS knt FROM Depts NATURAL LEFT JOIN Clerks GROUP by deptno A Depts tuple is included (with NULL for empno) from every department that doesn't have a matching clerk

46 46 © Ellis Cohen 2001-2008 Another Factoring Exercise For each department, list the average salary of the employees in that department who are project managers. You may ignore departments that don't have project managers empno ename job mgr hiredate sal comm deptno Projs pno pname pmgr persons budget pstart pend Emps avg() What's the view?

47 47 © Ellis Cohen 2001-2008 View for Factoring Exercise ProjMgrs: Employees who are project managers For each department, list the average salary of the ProjMgrs Write using factored views

48 48 © Ellis Cohen 2001-2008 Another Factoring Exercise Answer For each department, list the average salary of the employees in that department who are project managers. Now, include depts w/o project managers, and identify depts by name WITH ProjMgrs AS (SELECT DISTINCT empno FROM (Emps JOIN Projs ON empno = pmgr)) SELECT deptno, avg(sal) FROM ProjMgrs NATURAL JOIN Emps GROUP BY deptno WITH ProjMgrs AS (SELECT DISTINCT empno, sal, deptno FROM Emps JOIN Projs ON empno = pmgr)) SELECT deptno, avg(sal) FROM ProjMgrs GROUP BY deptno

49 49 © Ellis Cohen 2001-2008 Answer with Outer Joins For each named department, list the average salary of the employees in that department who are project managers. Include departments without any project managers (they'll show a NULL average salary) WITH ProjMgrs AS (SELECT DISTINCT empno, sal, deptno FROM (Emps JOIN Projs ON empno = pmgr)) SELECT dname, avg(sal) FROM (Depts NATURAL LEFT JOIN ProjMgrs) GROUP BY dname

50 50 © Ellis Cohen 2001-2008 State Assertions Using Manifest Views

51 51 © Ellis Cohen 2001-2008 SQL State Assertions Using Counts (SELECT count(DISTINCT deptno) FROM Emps WHERE job = 'CLERK') = (SELECT count(*) FROM Depts) Every department has a clerk (assume every employee is assigned to a dept) the # of depts which have clerks =the # of depts If you have complex assertions, it can be difficult both to debug the assertion, and (if you are convinced the assertion is correct, but is not satisfied) to debug the data!

52 52 © Ellis Cohen 2001-2008 Manifest Views Manifest Views simplify enforcing & debugging constraints and debugging data which violate them, due to the following characteristics: 1)Manifest: 1)Manifest: Just by looking at the contents of the manifest view, it is easy to tell whether the constraint is satisfied. 2)Easy Checking: 2)Easy Checking: The constraint can be enforced simply and clearly based on the manifest view. 3)Summarization: 3)Summarization: The view summarizes the underlying data, keeping as much information as possible. It should not be empty or result in just one tuple if the constraint is satisfied. 4)Debugging: 4)Debugging: If the manifest view indicates that the constraint is not satisfied, it also provides useful information about which tuples in the underlying data are responsible for violating the constraint. What manifest view would be useful for the assertion: Every department has at least one clerk

53 53 © Ellis Cohen 2001-2008 Manifest View Definition Define a view that indicates the # of clerks in each department 102 201 303 400 deptno nclerks NumDeptClerks Why is this a good manifest view? (based on the principles of manifest views)

54 54 © Ellis Cohen 2001-2008 Manifest View Validation 1.Manifest Just by looking at the view contents, it is possible to tell whether the constraint is satisfied. 2.Easy Checking Check each tuple of the view: fails if nclerks = 0 3.Summarization Yes, and the view is not empty and doesn’t have just a single tuple if the constraint is satisfied 4.Debugging If a tuple has nclerks = 0, the problem is clearly with the corresponding dept Given this view, write the SQL assertion that ensures that nclerks does not contain a zero

55 55 © Ellis Cohen 2001-2008 View-Based Assertion Given NumDeptClerks ( deptno, nclerks ) NOT EXISTS( SELECT * FROM NumDeptClerks WHERE nclerks = 0 ) (SELECT count(*) FROM NumDeptClerks WHERE nclerks = 0) = 0 (SELECT nclerks FROM NumDeptClerks) ALL > 0 Define NumDeptClerks

56 56 © Ellis Cohen 2001-2008 Defining NumDeptClerks Count the number of clerks in each department CREATE VIEW NumDeptClerks AS SELECT d.deptno, count(empno) AS knt FROM Depts d LEFT JOIN Emps e ON d.deptno = e.deptno AND job = 'CLERK' GROUP BY deptno Views can be defined using factored queries!

57 57 © Ellis Cohen 2001-2008 Using a Factored View Count the number of clerks in each department CREATE VIEW NumDeptClerks AS WITH Clerks AS (SELECT * FROM Emps WHERE job = 'CLERK') SELECT deptno, count(empno) AS knt FROM Depts NATURAL LEFT JOIN Clerks GROUP BY deptno Views can be defined using factored queries!

58 58 © Ellis Cohen 2001-2008 Another Problem Given Projs( pno, owner ) Tasks( tno, pno, owner ) And we want to enforce the constraint that The tasks in every project have the same owner as the project (assuming that every project & task has an owner) NOT EXISTS( SELECT * FROM Projs p JOIN Tasks t ON p.pno = t.pno AND p.owner != t.owner) What is a good manifest view?

59 59 © Ellis Cohen 2001-2008 Manifest View Definition For each project, count the # of tasks for each different task owner (and show the project & task owner) 103417 8 202619 23 20261930211 304077 14 pno powner towner knt PTOwn Why is this a good manifest view? (based on the principles of manifest views)

60 60 © Ellis Cohen 2001-2008 Manifest View Validation 1.Manifest Just by looking at the view contents, it is possible to tell whether the constraint is satisfied. 2.Easy Checking Check each tuple of the view: fails if powner != towner 3.Summarization Yes, and the view is not empty and doesn’t have just a single tuple if the constraint is satisfied 4.Debugging If a tuple has powner != towner, the problem is clearly with the corresponding dept Given this view, write the SQL assertion that ensures the constraint is satisfied

61 61 © Ellis Cohen 2001-2008 View-Based Assertion Given PTOwn ( pno, powner, towner, knt ) NOT EXISTS( SELECT * FROM PTOwn WHERE powner != towner ) (SELECT count(*) FROM NumDeptClerks WHERE powner != towner) = 0 Define PTOwn

62 62 © Ellis Cohen 2001-2008 Defining PTOwn CREATE VIEW PTOwn AS SELECT p.pno, p.owner AS powner, t.owner AS towner, count(*) AS knt FROM Projs p JOIN Tasks t ON p.pno = t.tno GROUP BY p.pno, p.owner, t.owner

63 63 © Ellis Cohen 2001-2008 Views & CHECK Constraints Standard SQL does not allow CHECK constraints to be defined and enforced on views. Would it be useful if it did? If SQL enforced CHECK constraints on views, would CREATE ASSERTION still be necessary?

64 64 © Ellis Cohen 2001-2008 View-Based Assertion Problem CREATE ASSERTION GuessThis CHECK( NOT EXISTS( SELECT * FROM DeptKnts WHERE knt NOT BETWEEN 2 AND 5 ) ) CREATE VIEW DeptKnts AS SELECT deptno, count(empno) AS knt FROM Depts NATURAL LEFT JOIN Emps GROUP BY deptno What is the conceptual constraint which corresponds to this assertion? Why is an outer join needed?

65 65 © Ellis Cohen 2001-2008 Expressing Cardinality Constraints CREATE ASSERTION GuessThis CHECK( NOT EXISTS( SELECT * FROM DeptKnts WHERE knt NOT BETWEEN 2 AND 5 ) ) CREATE VIEW DeptKnts AS SELECT deptno, count(empno) AS knt FROM Depts NATURAL LEFT JOIN Emps GROUP BY deptno 102 201 303 400 deptno knt DeptKnts # of employees in each dept must be between 2 and 5 Dept Employee employs 2..5 Reason for outer join

66 66 © Ellis Cohen 2001-2008 Complex State Assertions

67 67 © Ellis Cohen 2001-2008 Manifest View Divide & Conquer An assertion may be so complicated that the manifest view needed must be written using other views Each of these sub-views must be inspectable

68 68 © Ellis Cohen 2001-2008 Complex Assertion Problem Every manager (except the President) works at the same location as the employees they directly manage Manifest View: EmpMgrView empno – employee's number eloc – employee's location mloc – their mgr's location mjob – their mgr's job Assertion: NOT EXISTS( SELECT * FROM EmpMgrView WHERE mjob != 'PRESIDENT' AND eloc <> mloc )

69 69 © Ellis Cohen 2001-2008 Defining EmpMgrView EmpInfo: empno – employee number loc – their location job – their job EmpMgrInfo: empno – employee number loc – their manager's location (NULL if no mgr) job – their manager's job (NULL if no mgr) CREATE VIEW EmpMgrView AS SELECT e.empno, e.loc AS eloc, m.loc AS mloc, m.job AS mjob FROM (EmpInfo e JOIN EmpMgrInfo m ON e.empno = m.empno)

70 70 © Ellis Cohen 2001-2008 Defining EmpMgrInfo CREATE VIEW EmpMgrInfo AS SELECT e.empno, m.loc, m.job FROM (Emps e LEFT JOIN EmpInfo m ON e.mgr = m.empno) CREATE VIEW EmpInfo AS SELECT empno, loc, job FROM (Emps NATURAL JOIN Depts)

71 71 © Ellis Cohen 2001-2008 EmpInfo & EmpMgrInfo empno ename job mgr hiredate sal comm deptno Emps e EmpInfo m empno loc job empno ename job mgr hiredate sal comm deptno Emps Depts deptno dname loc EmpInfo EmpMgrInfo Only the view's result attributes can be joined or used as a result attribute of the main join diagram!

72 72 © Ellis Cohen 2001-2008 Join Diagram with Expanded View empno ename job mgr hiredate sal comm deptno Emps e EmpInfo m empno ename job mgr hiredate sal comm deptno Emps Depts deptno dname loc empno ename job mgr hiredate sal comm deptno Emps Depts deptno dname loc EmpInfo EmpMgrInfo empno ename job mgr hiredate sal comm deptno Emps e EmpInfo m empno loc job EmpMgrInfo Only the view's result attributes can be joined or used as a result attribute of the main join diagram!

73 73 © Ellis Cohen 2001-2008 Manifest Factored Assertion WITH EmpInfo AS ( SELECT empno, loc, job FROM (Emps NATURAL JOIN Depts)), EmpMgrInfo AS ( SELECT e.empno, m.loc, m.job FROM (Emps e LEFT JOIN EmpInfo m ON e.mgr = m.empno), EmpMgrView AS ( SELECT e.empno, e.loc AS eloc, m.loc AS mloc, m.job AS mjob FROM (EmpInfo e JOIN EmpMgrInfo m ON e.empno = m.empno)) NOT EXISTS( SELECT * FROM EmpMgrView WHERE mjob != 'PRESIDENT' AND eloc <> mloc )

74 74 © Ellis Cohen 2001-2008 View-Based Modification

75 75 © Ellis Cohen 2001-2008 Views-Based UPDATE UPDATE HiEmps SET comm = 1.3 * comm only updates the commissions of the high-paid employees It is equivalent to UPDATE Emps SET comm = 1.3 * comm WHERE sal > 1500 CREATE VIEW HiEmps AS SELECT * FROM Emps WHERE sal > 1500 An update to a view updates the tuples in the underlying base table which is mapped to the view

76 76 © Ellis Cohen 2001-2008 Non-Updateable Views UPDATE AvgJobSals SET avgsal = 1.27 * avgsal Not all views are updatable CREATE VIEW AvgJobSals AS SELECT job, avg(sal) AS avgsal FROM Emps GROUP BY job Remember, AvgJobSals is not a table, it's just a description based on the base table Emps. If you changed avgsal, what would you change in Emps?

77 77 © Ellis Cohen 2001-2008 Updating Join-Based Views UPDATE EmpDeptView SET comm = 1.3 * comm CREATE VIEW EmpDeptView AS SELECT * FROM (Emps NATURAL JOIN Depts) WHERE sal > 1500 The intent is to change the commissions of all the tuples which are visible through the view: These are exactly those employees whose sal > 1500 The DB can achieve this effect by updating tuples in one of the underlying base tables: Emps UPDATE works so long as the intended effect can be achieved by updating a set of tuples in one of the underlying base tables that map 1:1 to the tuples affected in the view UPDATE Emps SET comm = comm * 1.3 WHERE sal > 1500

78 78 © Ellis Cohen 2001-2008 Can't Update loc Through View empno ename sal deptno 7499ALLEN160010 7654MARTIN125010 7698BLAKE285020 7839KING500020 7844TURNER150010 7986STERN150030 Emps WHERE sal > 1500 10ACCOUNTINGBOSTON 20RESEARCHLA 30SALESPARIS 40OPERATIONSPODUNK deptno dname loc Depts CREATE VIEW EmpDeptView AS SELECT * FROM (Emps NATURAL JOIN Depts) WHERE sal > 1500 UPDATE EmpDeptView SET loc = 'ARUBA' If we change dept 10's loc to ARUBA, then MARTIN & TURNER are now in ARUBA, not just ALLEN

79 79 © Ellis Cohen 2001-2008 Non-Updateable Join-Based Views CREATE VIEW EmpDeptView AS SELECT * FROM (Emps NATURAL JOIN Depts) WHERE sal > 1500 UPDATE EmpDeptView SET loc = 'ARUBA' The intent is to change the department location of just the high-paid employees to ARUBA, but it's not clear how to do this. If we consider the depts any of them are in, and change those dept locs to ARUBA, we are also changing the location of the lower-paid employees who are working in those departments. The problem is that loc is in Depts, so we must update Depts, but there's NOT a 1:1 mapping of Dept tuples to the affected tuples in EmpDeptView UPDATE works so long as the intended effect can be achieved by updating a set of tuples in one of the underlying base tables that map 1:1 to the tuples affected in the view

80 80 © Ellis Cohen 2001-2008 Can Delete Through View Based On loc empno ename sal deptno 7499ALLEN160010 7654MARTIN125010 7698BLAKE285020 7839KING500020 7844TURNER150010 7986STERN150030 Emps WHERE sal > 1500 10ACCOUNTINGBOSTON 20RESEARCHLA 30SALESPARIS 40OPERATIONSPODUNK deptno dname loc Depts CREATE VIEW EmpDeptView AS SELECT * FROM (Emps NATURAL JOIN Depts) WHERE sal > 1500 DELETE FROM EmpDeptView WHERE loc = 'BOSTON'

81 81 © Ellis Cohen 2001-2008 View-Based DELETE DELETE FROM EmpDeptView WHERE job = 'ANALYST' CREATE VIEW EmpDeptView AS SELECT * FROM (Emps NATURAL JOIN Depts) WHERE sal > 1500 Easy. Equivalent to DELETE FROM Emps WHERE (job = 'ANALYST') AND (sal > 1500) DELETE FROM EmpDeptView WHERE loc = 'BOSTON' Deletes high-paid employees from Emps who work for a department located in Boston. We'll revisit this when we discuss subqueries DELETE works so long as the intended effect can be achieved by deleting a set of tuples in one of the underlying base tables that map 1:1 to the tuples deleted from the view

82 82 © Ellis Cohen 2001-2008 View-Based INSERT INSERT INTO EmpDeptView( empno, ename, deptno ) VALUES (3417, 'BUCK', 30) CREATE VIEW EmpDeptView AS SELECT * FROM (Emps NATURAL JOIN Depts) WHERE sal > 1500 INSERT works so long as the effect can be achieved by inserting the tuples in one of the base tables. No problem. The corresponding tuple is inserted into the Emps table. Problematic. How do we arrange that just this department 30 employee is located in ARUBA? INSERT INTO EmpDeptView( empno, ename, deptno, loc ) VALUES (3417, 'BUCK', 30, 'ARUBA')

83 83 © Ellis Cohen 2001-2008 The CHECK OPTION CREATE VIEW HiEmps AS SELECT * FROM Emps WHERE sal > 1500 WITH CHECK OPTION CONSTRAINT HiEmps_Check INSERT INTO HiEmps( empno, ename, sal ) VALUES ( 3333, 'Sam Sham', 1200 ) This inserts a tuple into Emps which actually will NOT appear in the view. SQL ordinarily allows this. WITH CHECK OPTION prevents inserts & updates from inserting or updating tuples so that they don't appear in the view The optional CONSTRAINT names this constraint

84 84 © Ellis Cohen 2001-2008 Read Only Views CREATE VIEW HiEmps AS SELECT * FROM Emps WHERE sal > 1500 WITH READ ONLY If a view is specified as READ ONLY (Oracle-specific) It can only be selected from It CANNOT be used to insert, delete, or update through

85 85 © Ellis Cohen 2001-2008 Materialized Views

86 86 © Ellis Cohen 2001-2008 Cost of Using Views Typically a view involves joins across multiple tables. Every time a view is queried, a join must be done. This can be expensive if the view is used frequently Suppose –The view is used frequently –The underlying tables on which the view is based do not change very often

87 87 © Ellis Cohen 2001-2008 Example View CREATE VIEW EmpDeptsView AS SELECT empno, ename, job, deptno, dname FROM Emps NATURAL JOIN Depts Suppose Emps and Depts are changed infrequently Everytime EmpDeptsView is accessed, Emps and Depts have to be joined

88 88 © Ellis Cohen 2001-2008 Materialized Views A materialized view is an actual persistent table which contains the data to be viewed from underlying tables. Every time the underlying tables are changed, the materialized view must also be changed to keep it consistent (sometimes this is done on a regular schedule instead of on every change) Materialized Views are frequently read only. Sometimes they support updates propagated back to their base tables.

89 89 © Ellis Cohen 2001-2008 Defining Materialized Views CREATE MATERIALIZED VIEW EmpDeptsView AS SELECT empno, ename, job, deptno, dname FROM Emps NATURAL JOIN Depts EmpDeptsView is now a table that will be built immediately, and updated whenever a change is made in the underlying base tables (Oracle only) Developers can use triggers to define materialized views in systems which do not support them directly


Download ppt "1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen 2002-2008 Views These slides are licensed under."

Similar presentations


Ads by Google