Views. Objectives Create views Modify/Drop Views Insert/Delete/Update to/from views Retrieve data...

Post on 05-Jan-2016

221 views 0 download

Transcript of Views. Objectives Create views Modify/Drop Views Insert/Delete/Update to/from views Retrieve data...

Views

ObjectivesCreate viewsModify/Drop ViewsInsert/Delete/Update to/from viewsRetrieve data from views

FactsViews as logical representation of dataViews are queried like tablesViews are objects similar to tablesViews are stored queriesEvery time a view is uses the query is run

(Views are not stored database)

3

Advantages of ViewsRestrict database accessRepresent data from different tablesMake complex query easyCalculate values of formulaRepresent different views of the same dataViews can be created from other views

4

Creating ViewsCREATE [OR REPLACE] VIEW

nameAS sub-query[WITH READ ONLY]

5

Creating ViewsExample:

CREATE OR REPLACE VIEW salesEmplAS

SELECT *FROM testdata.EmployeeWHERE dept=‘Sales’;

6

Check the Structure of ViewsDESC salesEmpl;

Name Null? TypeF_Name VARCHAR2(20)L_Name VARCHAR2(20)SSN NUMBER(9)Dept VARCHAR2(20)B_Date DATE

7

Check the Content of Views

SELECT *FROM SalesEmpl;

Retrieve data from Views

SELECT L_Name, F_Name, SSNFROM SalesEmplWHERE TO_CHAR(B_Date, ‘YYYY’)=1973;

8

Column Aliases:CREATE VIEW GoodStudents AS

SELECT Name, SSN ID, Major Area, Email Contact

FROM StudentsWhere GPA>3;

Alternative Renaming:

CREATE OR REPLACE VIEW GoodStudents(Name, ID, Area, Contact)AS

SELECT Name, SSN, Major, EmailFROM StudentsWHERE GPA>3;

9

Use of Functions:CREATE VIEW EmployeeData

(Dept, MinSal, MaxSal, AvgSal, CountEmp)AS

SELECT Dept, MIN(PayRate), Max(PayRate), AVG (PayRate), Count(*)

FROM Employee;

10

Use of Functions:SELECT * FROM EmployeeData;

How to modify Views?

11

SELECT only Views:

CREATE View EmployeeDataAS

SELECT L_Name, F_Name, DeptFROM EmployeeWITH READ ONLY;

Why do we need a read only view?

12

Delete Views:

DROP VIEW Name)

DROP VIEW EmployeeData;

13

Check the list of views

SELECT *FROM USER_VIEWS;

14

INSERT Data into View

INSERT INTO GoodStudent(ID, Name, Area, Contact)VALUES (211202111, ‘John Smith’,

‘COSC’, ‘Jsmith@fsu.edu’);

15

Insert with NULL value:

INSERT INTO GoodStudent(ID, Name, Area, Contact)

VALUES (211202111, ‘John Smith’, NULL, ‘Jsmith@fsu.edu’);

16

Delete data from views:

DELETE GoodStudentWHERE ID=211202111;

Update Views:UPDATE GoodStudentSET Area=‘MATH’WHERE ID=211202111;

17

Create Views from Multiple tableCREATE OR REPLACE VIEW SalesInfo

(Name, ID, Item, Cost)AS

SELECT F_Name || ‘ ‘ || L_Name, ID, HowMany, Price

FROM Employee, SalesWHERE ID=E_ID;

18