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

Slides:



Advertisements
Similar presentations
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Advertisements

1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Natural Joins These slides are licensed.
Copyright  Oracle Corporation, All rights reserved. 10 Creating and Managing Tables.
SQL Subqueries Objectives of the Lecture : To consider the general nature of subqueries. To consider simple versus correlated subqueries. To consider the.
12-1 Copyright  Oracle Corporation, All rights reserved. What Is a View? EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
1Eyad Alshareef Enhanced Guide to Oracle 10g Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Extended SQL & The Relational Calculus.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Copyright  Oracle Corporation, All rights reserved. 6 Writing Correlated Subqueries.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Introduction to Objects & Databases These.
o At the end of this lesson, you will be able to:  Describe the life-cycle development phases  Discuss the theoretical and physical aspects of a relational.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen M:N Relationships & Bridge Classes These.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Relationship Classes & N-ary Relationships.
Copyright  Oracle Corporation, All rights reserved. 1 Writing Basic SQL Statements.
1 ICS 184: Introduction to Data Management Lecture Note 10 SQL as a Query Language (Cont.)
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Basic Relational Algebra These slides.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Advanced Normalization These slides are.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen :1 Relationships These slides are licensed.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Introduction to Relational Databases &
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Cursors These slides are licensed under.
2 Writing Basic SELECT Statements. 1-2 Copyright  Oracle Corporation, All rights reserved. Capabilities of SQL SELECT Statements Selection Projection.
Copyright  Oracle Corporation, All rights reserved. Writing Basic SQL Statements.
1 Information Retrieval and Use (IRU) CE An Introduction To SQL Part 1.
SELECT Statements Lecture Notes Sree Nilakanta Fall 2010 (rev)
An Introduction To SQL - Part 1 (Special thanks to Geoff Leese)
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Enforcing State & Transition Constraints.
SQL- DQL (Oracle Version). 2 SELECT Statement Syntax SELECT [DISTINCT] column_list FROM table_list [WHERE conditional expression] [GROUP BY column_list]
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Basic SQL These slides are licensed under.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Maintaining Session State in the Data.
Session 2: SQL (A): Parts 1 and 2 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Relational Mapping with Constraints &
SQL: Part 1 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram. Not for commercial.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Maintaining Session State in the Data.
I-1 Copyright س Oracle Corporation, All rights reserved. Data Retrieval.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Implementing The Middle Tier These slides.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Advanced Relational Algebra These slides.
Copyright  Oracle Corporation, All rights reserved. 12 Creating Views.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Subqueries These slides are licensed under.
An Introduction To SQL Part 2 (Special thanks to Geoff Leese)
1 Information Retrieval and Use (IRU) An Introduction To SQL Part 2.
Insert & Delete Objectives of the Lecture : To consider the insertion of tuples into a relation; To consider the deletion of tuples from a relation; To.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Object-Relational Database Programming.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Using Data Structures in Embedded Programs.
Copyright س Oracle Corporation, All rights reserved. I Introduction.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Relational State Assertions These slides.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Collection Operators These slides are.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Grouping These slides are licensed under.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Collection Operators These slides are.
Copyright س Oracle Corporation, All rights reserved. 12 Creating Views.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Inner Joins These slides are licensed.
CSCI N311: Oracle Database Programming 5-1 Chapter 15: Changing Data: insert, update, delete Insert Rollback Commit Update Delete Insert Statement –Allows.
Writing Basic SQL Statements. Objectives After completing this lesson, you should be able to do the following: –List the capabilities of SQL SELECT statements.
SQL Statements SELECT INSERTUPDATEDELETECREATEALTERDROPRENAMETRUNCATECOMMITROLLBACKSAVEPOINTGRANTREVOKE Data Retrieval Language (DRL) Data Retrieval Language.
Copyright س Oracle Corporation, All rights reserved. 1 Writing Basic SQL Statements.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Relational Normalization Theory
Aggregating Data Using Group Functions
Subqueries.
Subqueries Schedule: Timing Topic 25 minutes Lecture
Aggregating Data Using Group Functions
Manipulating Data Schedule: Timing Topic 40 minutes Lecture
Writing Correlated Subqueries
What Is a View? EMPNO ENAME JOB EMP Table EMPVU10 View
Copyright © Ellis Cohen Consistency & Initialization
Writing Basic SQL Statements
Subqueries Schedule: Timing Topic 25 minutes Lecture
Subqueries Schedule: Timing Topic 25 minutes Lecture
Copyright © Ellis Cohen
Database Programming Using Oracle 11g
Copyright © Ellis Cohen Enforcing State Constraints
Presentation transcript:

1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen 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

2 © Ellis Cohen 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 © Ellis Cohen Introduction to Views

4 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen View-Based Problem Solving

12 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen Views and Inspectability

20 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen Table Expressions, Inline Views & Factoring

28 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen Using Views with Grouping

32 © Ellis Cohen 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 © Ellis Cohen Divide & Conquer View deptno knt 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 © Ellis Cohen Query Based on View deptno knt 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 © Ellis Cohen Divide & Conquer Code WITH DeptKnts AS ( SELECT deptno, count(*) AS knt FROM Emps GROUP BY deptno ) SELECT count(*) FROM DeptKnts WHERE knt >= 3

36 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen Group Restriction Using Views ANALYST12500 CLERK21900 DEPTMGR32000 job dknt avgsal empno job deptno sal 7839ANALYST ANALYST CLERK CLERK CLERK DEPTMGR DEPTMGR DEPTMGR 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 © Ellis Cohen Using and Defining Views ANALYST12500 CLERK21900 DEPTMGR32000 job dknt avgsal empno job deptno sal 7839ANALYST ANALYST CLERK CLERK CLERK DEPTMGR DEPTMGR DEPTMGR 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 © Ellis Cohen 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 © Ellis Cohen Views and Outer Joins

44 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen State Assertions Using Manifest Views

51 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen Manifest View Definition Define a view that indicates the # of clerks in each department deptno nclerks NumDeptClerks Why is this a good manifest view? (based on the principles of manifest views)

54 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen Manifest View Definition For each project, count the # of tasks for each different task owner (and show the project & task owner) pno powner towner knt PTOwn Why is this a good manifest view? (based on the principles of manifest views)

60 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 deptno knt DeptKnts # of employees in each dept must be between 2 and 5 Dept Employee employs 2..5 Reason for outer join

66 © Ellis Cohen Complex State Assertions

67 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen View-Based Modification

75 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen Can't Update loc Through View empno ename sal deptno 7499ALLEN MARTIN BLAKE KING TURNER STERN Emps WHERE sal > ACCOUNTINGBOSTON 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 © Ellis Cohen 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 © Ellis Cohen Can Delete Through View Based On loc empno ename sal deptno 7499ALLEN MARTIN BLAKE KING TURNER STERN Emps WHERE sal > ACCOUNTINGBOSTON 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen Materialized Views

86 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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 © Ellis Cohen 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