SlideShare a Scribd company logo
11
Copyright © Oracle Corporation, 2001. All rights reserved.
Creating Views
11-2 Copyright © Oracle Corporation, 2001. All rights reserved.
Objectives
After completing this lesson, you should be able
to do the following:
• Describe a view
• Create, alter the definition of, and drop a view
• Retrieve data through a view
• Insert, update, and delete data through
a view
• Create and use an inline view
• Perform “Top-N” analysis
11-3 Copyright © Oracle Corporation, 2001. All rights reserved.
Database Objects
Description
Basic unit of storage; composed of rows
and columns
Logically represents subsets of data from
one or more tables
Generates primary key values
Improves the performance of some queries
Alternative name for an object
Object
Table
View
Sequence
Index
Synonym
11-4 Copyright © Oracle Corporation, 2001. All rights reserved.
What Is a View?
EMPLOYEES Table:
11-5 Copyright © Oracle Corporation, 2001. All rights reserved.
Why Use Views?
• To restrict data access
• To make complex queries easy
• To provide data independence
• To present different views of the same data
11-6 Copyright © Oracle Corporation, 2001. All rights reserved.
Simple Views
and Complex Views
Feature Simple Views Complex Views
Number of tables One One or more
Contain functions No Yes
Contain groups of data No Yes
DML operations
through a view Yes Not always
11-7 Copyright © Oracle Corporation, 2001. All rights reserved.
Creating a View
• You embed a subquery within the CREATE VIEW
statement.
• The subquery can contain complex SELECT syntax.
CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view
[(alias[, alias]...)]
AS subquery
[WITH CHECK OPTION [CONSTRAINT constraint]]
[WITH READ ONLY [CONSTRAINT constraint]];
CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view
[(alias[, alias]...)]
AS subquery
[WITH CHECK OPTION [CONSTRAINT constraint]]
[WITH READ ONLY [CONSTRAINT constraint]];
11-8 Copyright © Oracle Corporation, 2001. All rights reserved.
Creating a View
• Create a view, EMPVU80, that contains details of
employees in department 80.
• Describe the structure of the view by using the
iSQL*Plus DESCRIBE command.
DESCRIBE empvu80DESCRIBE empvu80
CREATE VIEW empvu80
AS SELECT employee_id, last_name, salary
FROM employees
WHERE department_id = 80;
View created.View created.
11-9 Copyright © Oracle Corporation, 2001. All rights reserved.
Creating a View
• Create a view by using column aliases in the
subquery.
• Select the columns from this view by the given
alias names.
CREATE VIEW salvu50
AS SELECT employee_id ID_NUMBER, last_name NAME,
salary*12 ANN_SALARY
FROM employees
WHERE department_id = 50;
View created.View created.
11-10 Copyright © Oracle Corporation, 2001. All rights reserved.
Retrieving Data from a View
SELECT *
FROM salvu50;
11-11 Copyright © Oracle Corporation, 2001. All rights reserved.
Querying a View
USER_VIEWSUSER_VIEWS
EMPVU80EMPVU80
SELECT employee_id,
last_name, salary
FROM employees
WHERE department_id=80;
iSQL*Plus
SELECT *
FROM empvu80;
EMPLOYEES
Oracle ServerOracle Server
11-12 Copyright © Oracle Corporation, 2001. All rights reserved.
Modifying a View
• Modify the EMPVU80 view by using CREATE OR
REPLACE VIEW clause. Add an alias for each
column name.
• Column aliases in the CREATE VIEW clause are
listed in the same order as the columns in the
subquery.
CREATE OR REPLACE VIEW empvu80
(id_number, name, sal, department_id)
AS SELECT employee_id, first_name || ' ' || last_name,
salary, department_id
FROM employees
WHERE department_id = 80;
View created.View created.
11-13 Copyright © Oracle Corporation, 2001. All rights reserved.
Creating a Complex View
Create a complex view that contains group functions
to display values from two tables.
CREATE VIEW dept_sum_vu
(name, minsal, maxsal, avgsal)
AS SELECT d.department_name, MIN(e.salary),
MAX(e.salary),AVG(e.salary)
FROM employees e, departments d
WHERE e.department_id = d.department_id
GROUP BY d.department_name;
View created.View created.
11-14 Copyright © Oracle Corporation, 2001. All rights reserved.
Rules for Performing
DML Operations on a View
• You can perform DML operations on simple views.
• You cannot remove a row if the view contains the
following:
– Group functions
– A GROUP BY clause
– The DISTINCT keyword
– The pseudocolumn ROWNUM keyword
11-15 Copyright © Oracle Corporation, 2001. All rights reserved.
Rules for Performing
DML Operations on a View
You cannot modify data in a view if it contains:
• Group functions
• A GROUP BY clause
• The DISTINCT keyword
• The pseudocolumn ROWNUM keyword
• Columns defined by expressions
11-16 Copyright © Oracle Corporation, 2001. All rights reserved.
Rules for Performing
DML Operations on a View
You cannot add data through a view if the view
includes:
• Group functions
• A GROUP BY clause
• The DISTINCT keyword
• The pseudocolumn ROWNUM keyword
• Columns defined by expressions
• NOT NULL columns in the base tables that are not
selected by the view
11-17 Copyright © Oracle Corporation, 2001. All rights reserved.
• You can ensure that DML operations performed on
the view stay within the domain of the view by
using the WITH CHECK OPTION clause.
• Any attempt to change the department number for
any row in the view fails because it violates the
WITH CHECK OPTION constraint.
CREATE OR REPLACE VIEW empvu20
AS SELECT *
FROM employees
WHERE department_id = 20
WITH CHECK OPTION CONSTRAINT empvu20_ck ;
View created.View created.
Using the WITH CHECK OPTION Clause
11-18 Copyright © Oracle Corporation, 2001. All rights reserved.
Denying DML Operations
• You can ensure that no DML operations occur by
adding the WITH READ ONLY option to your view
definition.
• Any attempt to perform a DML on any row in the
view results in an Oracle server error.
11-19 Copyright © Oracle Corporation, 2001. All rights reserved.
Denying DML Operations
CREATE OR REPLACE VIEW empvu10
(employee_number, employee_name, job_title)
AS SELECT employee_id, last_name, job_id
FROM employees
WHERE department_id = 10
WITH READ ONLY;
View created.View created.
11-20 Copyright © Oracle Corporation, 2001. All rights reserved.
Removing a View
You can remove a view without losing data because a
view is based on underlying tables in the database.
DROP VIEW empvu80;
View dropped.View dropped.
DROP VIEW view;DROP VIEW view;
11-21 Copyright © Oracle Corporation, 2001. All rights reserved.
Inline Views
• An inline view is a subquery with an alias (or
correlation name) that you can use within a SQL
statement.
• A named subquery in the FROM clause of the main
query is an example of an inline view.
• An inline view is not a schema object.
11-22 Copyright © Oracle Corporation, 2001. All rights reserved.
Top-N Analysis
• Top-N queries ask for the n largest or smallest
values of a column. For example:
– What are the ten best selling products?
– What are the ten worst selling products?
• Both largest values and smallest values sets are
considered Top-N queries.
11-23 Copyright © Oracle Corporation, 2001. All rights reserved.
Performing Top-N Analysis
The high-level structure of a Top-N analysis
query is:
SELECT [column_list], ROWNUM
FROM (SELECT [column_list]
FROM table
ORDER BY Top-N_column)
WHERE ROWNUM <= N;
SELECT [column_list], ROWNUM
FROM (SELECT [column_list]
FROM table
ORDER BY Top-N_column)
WHERE ROWNUM <= N;
11-24 Copyright © Oracle Corporation, 2001. All rights reserved.
Example of Top-N Analysis
To display the top three earner names and salaries
from the EMPLOYEES table:
SELECT ROWNUM as RANK, last_name, salary
FROM (SELECT last_name,salary FROM employees
ORDER BY salary DESC)
WHERE ROWNUM <= 3;
31 2
1 2 3
11-25 Copyright © Oracle Corporation, 2001. All rights reserved.
Summary
In this lesson, you should have learned that a view is
derived from data in other tables or views and
provides the following advantages:
• Restricts database access
• Simplifies queries
• Provides data independence
• Provides multiple views of the same data
• Can be dropped without removing the underlying
data
• An inline view is a subquery with an alias name.
• Top-N analysis can be done using subqueries and
outer queries.
11-26 Copyright © Oracle Corporation, 2001. All rights reserved.
Practice 11 Overview
This practice covers the following topics:
• Creating a simple view
• Creating a complex view
• Creating a view with a check constraint
• Attempting to modify data in the view
• Displaying view definitions
• Removing views

More Related Content

PPTX
SQL(DDL & DML)
PPT
Producing Readable Output with iSQL*Plus - Oracle Data Base
PPT
Database Objects
PPTX
introdution to SQL and SQL functions
PPT
Single-Row Functions in orcale Data base
PPTX
SQL Queries Information
PPT
Aggregating Data Using Group Functions
PPT
Restricting and Sorting Data - Oracle Data Base
SQL(DDL & DML)
Producing Readable Output with iSQL*Plus - Oracle Data Base
Database Objects
introdution to SQL and SQL functions
Single-Row Functions in orcale Data base
SQL Queries Information
Aggregating Data Using Group Functions
Restricting and Sorting Data - Oracle Data Base

What's hot (20)

PPT
Displaying Data from Multiple Tables - Oracle Data Base
PPTX
Oracle Database View
PPTX
What is Link list? explained with animations
PPT
Sql oracle
PPT
Including Constraints -Oracle Data base
PPT
Sql ppt
PPT
Introduction to sql
PPTX
SQL - DML and DDL Commands
PDF
SQL Joins With Examples | Edureka
PPT
Controlling User Access -Data base
PPTX
sql function(ppt)
PPTX
STACKS IN DATASTRUCTURE
PPTX
Sql Basics And Advanced
PPT
Introduction to structured query language (sql)
PPSX
Data Structure (Queue)
PPT
Subqueries -Oracle DataBase
PDF
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
PPTX
SQL - Structured query language introduction
PPT
SQL Queries
Displaying Data from Multiple Tables - Oracle Data Base
Oracle Database View
What is Link list? explained with animations
Sql oracle
Including Constraints -Oracle Data base
Sql ppt
Introduction to sql
SQL - DML and DDL Commands
SQL Joins With Examples | Edureka
Controlling User Access -Data base
sql function(ppt)
STACKS IN DATASTRUCTURE
Sql Basics And Advanced
Introduction to structured query language (sql)
Data Structure (Queue)
Subqueries -Oracle DataBase
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
SQL - Structured query language introduction
SQL Queries
Ad

Viewers also liked (8)

PDF
Sql wksht-5
PDF
Views Oracle Database
PPTX
A New View of Database Views
PDF
DOC
Sql queires
DOC
Dbms lab questions
DOC
A must Sql notes for beginners
DOC
Sql queries with answers
Sql wksht-5
Views Oracle Database
A New View of Database Views
Sql queires
Dbms lab questions
A must Sql notes for beginners
Sql queries with answers
Ad

Similar to Creating Views - oracle database (20)

PPT
PPT
Les12[1]Creating Views
PPT
Sql views
PPT
PPTX
Oracle views
PPT
e computer notes - Creating views
PPT
Creating other schema objects
PPT
PDF
Lesson10
PPT
PPT
SQL WORKSHOP::Lecture 12
PDF
Database Oracle Basic
PPT
Oracle view
PPT
Chapter 8 Views in SQL-Introduction .ppt
PPT
Oracle training institute in hyderabad
PDF
SQL & Adv SQL - Basics and Advanced for Beginners
PPT
PPTX
DBMS weSDFDDDFDFDFDSSek 4,5 BSCS 6th.pptx
Les12[1]Creating Views
Sql views
Oracle views
e computer notes - Creating views
Creating other schema objects
Lesson10
SQL WORKSHOP::Lecture 12
Database Oracle Basic
Oracle view
Chapter 8 Views in SQL-Introduction .ppt
Oracle training institute in hyderabad
SQL & Adv SQL - Basics and Advanced for Beginners
DBMS weSDFDDDFDFDFDSSek 4,5 BSCS 6th.pptx

More from Salman Memon (20)

PPTX
PHP Array very Easy Demo
PPTX
Complete Lecture on Css presentation
PPTX
How to Use Dreamweaver cs6
PPTX
what is programming and its clear Concepts to the point
PPTX
Working with variables in PHP
PPT
Web forms and html (lect 5)
PPT
Web forms and html (lect 4)
PPT
Web forms and html (lect 3)
PPT
Web forms and html (lect 2)
PPT
Web forms and html (lect 1)
PPT
Managing in the Future Enterprise
PPT
Overview of Technology Management
PPT
Align Information Technology and Business Strategy
PPTX
WHITE BOX & BLACK BOX TESTING IN DATABASE
PPTX
Email security netwroking
PPTX
Email security - Netwroking
PPTX
Query decomposition in data base
PPTX
Time Management
PPTX
Multimedea device and routes
PPTX
Hash function
PHP Array very Easy Demo
Complete Lecture on Css presentation
How to Use Dreamweaver cs6
what is programming and its clear Concepts to the point
Working with variables in PHP
Web forms and html (lect 5)
Web forms and html (lect 4)
Web forms and html (lect 3)
Web forms and html (lect 2)
Web forms and html (lect 1)
Managing in the Future Enterprise
Overview of Technology Management
Align Information Technology and Business Strategy
WHITE BOX & BLACK BOX TESTING IN DATABASE
Email security netwroking
Email security - Netwroking
Query decomposition in data base
Time Management
Multimedea device and routes
Hash function

Recently uploaded (20)

PPTX
8 - Airport Statistical Forms icon related
PDF
Perth Immigration Agents Helping With Visa and Rent Stress
PPTX
Gujarat Tour Packages – Spiritual, Cultural & Scenic Journeys
PDF
Golden Triangle Tour A Complete Travel Guide.pdf
PDF
Explore Luxemburry.eu, the ancient of lands in Europe
PDF
Understanding Travel Insurance: Your Safety Net While Exploring the World
DOC
Best Astrologer in Agra .
PPTX
Best Tour and Travel- Travel Tips- Damanjit kaur
PPTX
Luxury in the Skies: Business Class Flights to Tokyo with FlightsLux
PDF
Nashik Kumbh Mela Package 2027 – Your Complete Travel Guide
PDF
Which Month is Best for Kailash Mansarovar Yatra.pdf
PDF
Memorable Outdoor Adventures with Premium River Rafting & Guided Tours
PDF
Why Everyone Misses These 7 Extraordinary Cities — And Why You Should Visit I...
PDF
Step Into Lima’s Magic Explore Peru’s Historic Capital From Anywhere.pdf
PDF
chopta tour package from delhi chopta tour
PPTX
Sri Lanka Tour Plan and places that can be visited during your leave
PPTX
Airline API Integration | Flight API Supplier
PDF
How Can Indians Visit Kailash Mansarovar.pdf
PPTX
How Indian Culture Is Perceived Around the World,Infouncle.pptx
PPTX
Exploring Chandigarh : A Perfect Travel Guide and Its Surroundings
8 - Airport Statistical Forms icon related
Perth Immigration Agents Helping With Visa and Rent Stress
Gujarat Tour Packages – Spiritual, Cultural & Scenic Journeys
Golden Triangle Tour A Complete Travel Guide.pdf
Explore Luxemburry.eu, the ancient of lands in Europe
Understanding Travel Insurance: Your Safety Net While Exploring the World
Best Astrologer in Agra .
Best Tour and Travel- Travel Tips- Damanjit kaur
Luxury in the Skies: Business Class Flights to Tokyo with FlightsLux
Nashik Kumbh Mela Package 2027 – Your Complete Travel Guide
Which Month is Best for Kailash Mansarovar Yatra.pdf
Memorable Outdoor Adventures with Premium River Rafting & Guided Tours
Why Everyone Misses These 7 Extraordinary Cities — And Why You Should Visit I...
Step Into Lima’s Magic Explore Peru’s Historic Capital From Anywhere.pdf
chopta tour package from delhi chopta tour
Sri Lanka Tour Plan and places that can be visited during your leave
Airline API Integration | Flight API Supplier
How Can Indians Visit Kailash Mansarovar.pdf
How Indian Culture Is Perceived Around the World,Infouncle.pptx
Exploring Chandigarh : A Perfect Travel Guide and Its Surroundings

Creating Views - oracle database

  • 1. 11 Copyright © Oracle Corporation, 2001. All rights reserved. Creating Views
  • 2. 11-2 Copyright © Oracle Corporation, 2001. All rights reserved. Objectives After completing this lesson, you should be able to do the following: • Describe a view • Create, alter the definition of, and drop a view • Retrieve data through a view • Insert, update, and delete data through a view • Create and use an inline view • Perform “Top-N” analysis
  • 3. 11-3 Copyright © Oracle Corporation, 2001. All rights reserved. Database Objects Description Basic unit of storage; composed of rows and columns Logically represents subsets of data from one or more tables Generates primary key values Improves the performance of some queries Alternative name for an object Object Table View Sequence Index Synonym
  • 4. 11-4 Copyright © Oracle Corporation, 2001. All rights reserved. What Is a View? EMPLOYEES Table:
  • 5. 11-5 Copyright © Oracle Corporation, 2001. All rights reserved. Why Use Views? • To restrict data access • To make complex queries easy • To provide data independence • To present different views of the same data
  • 6. 11-6 Copyright © Oracle Corporation, 2001. All rights reserved. Simple Views and Complex Views Feature Simple Views Complex Views Number of tables One One or more Contain functions No Yes Contain groups of data No Yes DML operations through a view Yes Not always
  • 7. 11-7 Copyright © Oracle Corporation, 2001. All rights reserved. Creating a View • You embed a subquery within the CREATE VIEW statement. • The subquery can contain complex SELECT syntax. CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view [(alias[, alias]...)] AS subquery [WITH CHECK OPTION [CONSTRAINT constraint]] [WITH READ ONLY [CONSTRAINT constraint]]; CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view [(alias[, alias]...)] AS subquery [WITH CHECK OPTION [CONSTRAINT constraint]] [WITH READ ONLY [CONSTRAINT constraint]];
  • 8. 11-8 Copyright © Oracle Corporation, 2001. All rights reserved. Creating a View • Create a view, EMPVU80, that contains details of employees in department 80. • Describe the structure of the view by using the iSQL*Plus DESCRIBE command. DESCRIBE empvu80DESCRIBE empvu80 CREATE VIEW empvu80 AS SELECT employee_id, last_name, salary FROM employees WHERE department_id = 80; View created.View created.
  • 9. 11-9 Copyright © Oracle Corporation, 2001. All rights reserved. Creating a View • Create a view by using column aliases in the subquery. • Select the columns from this view by the given alias names. CREATE VIEW salvu50 AS SELECT employee_id ID_NUMBER, last_name NAME, salary*12 ANN_SALARY FROM employees WHERE department_id = 50; View created.View created.
  • 10. 11-10 Copyright © Oracle Corporation, 2001. All rights reserved. Retrieving Data from a View SELECT * FROM salvu50;
  • 11. 11-11 Copyright © Oracle Corporation, 2001. All rights reserved. Querying a View USER_VIEWSUSER_VIEWS EMPVU80EMPVU80 SELECT employee_id, last_name, salary FROM employees WHERE department_id=80; iSQL*Plus SELECT * FROM empvu80; EMPLOYEES Oracle ServerOracle Server
  • 12. 11-12 Copyright © Oracle Corporation, 2001. All rights reserved. Modifying a View • Modify the EMPVU80 view by using CREATE OR REPLACE VIEW clause. Add an alias for each column name. • Column aliases in the CREATE VIEW clause are listed in the same order as the columns in the subquery. CREATE OR REPLACE VIEW empvu80 (id_number, name, sal, department_id) AS SELECT employee_id, first_name || ' ' || last_name, salary, department_id FROM employees WHERE department_id = 80; View created.View created.
  • 13. 11-13 Copyright © Oracle Corporation, 2001. All rights reserved. Creating a Complex View Create a complex view that contains group functions to display values from two tables. CREATE VIEW dept_sum_vu (name, minsal, maxsal, avgsal) AS SELECT d.department_name, MIN(e.salary), MAX(e.salary),AVG(e.salary) FROM employees e, departments d WHERE e.department_id = d.department_id GROUP BY d.department_name; View created.View created.
  • 14. 11-14 Copyright © Oracle Corporation, 2001. All rights reserved. Rules for Performing DML Operations on a View • You can perform DML operations on simple views. • You cannot remove a row if the view contains the following: – Group functions – A GROUP BY clause – The DISTINCT keyword – The pseudocolumn ROWNUM keyword
  • 15. 11-15 Copyright © Oracle Corporation, 2001. All rights reserved. Rules for Performing DML Operations on a View You cannot modify data in a view if it contains: • Group functions • A GROUP BY clause • The DISTINCT keyword • The pseudocolumn ROWNUM keyword • Columns defined by expressions
  • 16. 11-16 Copyright © Oracle Corporation, 2001. All rights reserved. Rules for Performing DML Operations on a View You cannot add data through a view if the view includes: • Group functions • A GROUP BY clause • The DISTINCT keyword • The pseudocolumn ROWNUM keyword • Columns defined by expressions • NOT NULL columns in the base tables that are not selected by the view
  • 17. 11-17 Copyright © Oracle Corporation, 2001. All rights reserved. • You can ensure that DML operations performed on the view stay within the domain of the view by using the WITH CHECK OPTION clause. • Any attempt to change the department number for any row in the view fails because it violates the WITH CHECK OPTION constraint. CREATE OR REPLACE VIEW empvu20 AS SELECT * FROM employees WHERE department_id = 20 WITH CHECK OPTION CONSTRAINT empvu20_ck ; View created.View created. Using the WITH CHECK OPTION Clause
  • 18. 11-18 Copyright © Oracle Corporation, 2001. All rights reserved. Denying DML Operations • You can ensure that no DML operations occur by adding the WITH READ ONLY option to your view definition. • Any attempt to perform a DML on any row in the view results in an Oracle server error.
  • 19. 11-19 Copyright © Oracle Corporation, 2001. All rights reserved. Denying DML Operations CREATE OR REPLACE VIEW empvu10 (employee_number, employee_name, job_title) AS SELECT employee_id, last_name, job_id FROM employees WHERE department_id = 10 WITH READ ONLY; View created.View created.
  • 20. 11-20 Copyright © Oracle Corporation, 2001. All rights reserved. Removing a View You can remove a view without losing data because a view is based on underlying tables in the database. DROP VIEW empvu80; View dropped.View dropped. DROP VIEW view;DROP VIEW view;
  • 21. 11-21 Copyright © Oracle Corporation, 2001. All rights reserved. Inline Views • An inline view is a subquery with an alias (or correlation name) that you can use within a SQL statement. • A named subquery in the FROM clause of the main query is an example of an inline view. • An inline view is not a schema object.
  • 22. 11-22 Copyright © Oracle Corporation, 2001. All rights reserved. Top-N Analysis • Top-N queries ask for the n largest or smallest values of a column. For example: – What are the ten best selling products? – What are the ten worst selling products? • Both largest values and smallest values sets are considered Top-N queries.
  • 23. 11-23 Copyright © Oracle Corporation, 2001. All rights reserved. Performing Top-N Analysis The high-level structure of a Top-N analysis query is: SELECT [column_list], ROWNUM FROM (SELECT [column_list] FROM table ORDER BY Top-N_column) WHERE ROWNUM <= N; SELECT [column_list], ROWNUM FROM (SELECT [column_list] FROM table ORDER BY Top-N_column) WHERE ROWNUM <= N;
  • 24. 11-24 Copyright © Oracle Corporation, 2001. All rights reserved. Example of Top-N Analysis To display the top three earner names and salaries from the EMPLOYEES table: SELECT ROWNUM as RANK, last_name, salary FROM (SELECT last_name,salary FROM employees ORDER BY salary DESC) WHERE ROWNUM <= 3; 31 2 1 2 3
  • 25. 11-25 Copyright © Oracle Corporation, 2001. All rights reserved. Summary In this lesson, you should have learned that a view is derived from data in other tables or views and provides the following advantages: • Restricts database access • Simplifies queries • Provides data independence • Provides multiple views of the same data • Can be dropped without removing the underlying data • An inline view is a subquery with an alias name. • Top-N analysis can be done using subqueries and outer queries.
  • 26. 11-26 Copyright © Oracle Corporation, 2001. All rights reserved. Practice 11 Overview This practice covers the following topics: • Creating a simple view • Creating a complex view • Creating a view with a check constraint • Attempting to modify data in the view • Displaying view definitions • Removing views

Editor's Notes

  • #2: Schedule:TimingTopic 20 minutesLecture 20 minutesPractice 40 minutesTotal
  • #3: Lesson Aim In this lesson, you learn how to create and use views. You also learn to query the relevant data dictionary object to retrieve information about views. Finally, you learn to create and use inline views, and perform Top-N analysis using inline views.
  • #5: What Is a View? You can present logical subsets or combinations of data by creating views of tables. A view is a logical table based on a table or another view. A view contains no data of its own but is like a window through which data from tables can be viewed or changed. The tables on which a view is based are called base tables. The view is stored as a SELECT statement in the data dictionary. Instructor Note Demo: 11_easyvu.sql Purpose: The view shown on the slide is created as follows: CREATE OR REPLACE VIEW simple_vu AS SELECT employee_id, last_name, salary FROM employees;
  • #6: Advantages of Views Views restrict access to the data because the view can display selective columns from the table. Views can be used to make simple queries to retrieve the results of complicated queries. For example, views can be used to query information from multiple tables without the user knowing how to write a join statement. Views provide data independence for ad hoc users and application programs. One view can be used to retrieve data from several tables. Views provide groups of users access to data according to their particular criteria. For more information, see Oracle9i SQL Reference, “CREATE VIEW.”
  • #7: Simple Views versus Complex Views There are two classifications for views: simple and complex. The basic difference is related to the DML (INSERT, UPDATE, and DELETE) operations. A simple view is one that: Derives data from only one table Contains no functions or groups of data Can perform DML operations through the view A complex view is one that: Derives data from many tables Contains functions or groups of data Does not always allow DML operations through the view
  • #8: Creating a View You can create a view by embedding a subquery within the CREATE VIEW statement. In the syntax: OR REPLACEre-creates the view if it already exists FORCEcreates the view regardless of whether or not the base tables exist NOFORCEcreates the view only if the base tables exist (This is the default.) viewis the name of the view aliasspecifies names for the expressions selected by the view’s query (The number of aliases must match the number of expressions selected by the view.) subqueryis a complete SELECT statement (You can use aliases for the columns in the SELECT list.) WITH CHECK OPTIONspecifies that only rows accessible to the view can be inserted or updated constraintis the name assigned to the CHECK OPTION constraint WITH READ ONLYensures that no DML operations can be performed on this view
  • #9: Creating a View (continued) The example on the slide creates a view that contains the employee number, last name, and salary for each employee in department 80. You can display the structure of the view by using the iSQL*Plus DESCRIBE command. Guidelines for creating a view: The subquery that defines a view can contain complex SELECT syntax, including joins, groups, and subqueries. The subquery that defines the view cannot contain an ORDER BY clause. The ORDER BY clause is specified when you retrieve data from the view. If you do not specify a constraint name for a view created with the WITH CHECK OPTION, the system assigns a default name in the format SYS_Cn. You can use the OR REPLACE option to change the definition of the view without dropping and re-creating it or regranting object privileges previously granted on it.
  • #10: Creating a View (continued) You can control the column names by including column aliases within the subquery. The example on the slide creates a view containing the employee number (EMPLOYEE_ID) with the alias ID_NUMBER, name (LAST_NAME) with the alias NAME, and annual salary (SALARY) with the alias ANN_SALARY for every employee in department 50. As an alternative, you can use an alias after the CREATE statement and prior to the SELECT subquery. The number of aliases listed must match the number of expressions selected in the subquery. CREATE VIEW salvu50 (ID_NUMBER, NAME, ANN_SALARY) AS SELECT employee_id, last_name, salary*12 FROM employees WHERE department_id = 50; View created. Instructor Note Let students know about materialized views or snapshots. The terms snapshot and materialized view are synonymous. Both refer to a table that contains the results of a query of one or more tables, each of which may be located on the same or on a remote database. The tables in the query are called master tables or detail tables. The databases containing the master tables are called the master databases. For more information regarding materialized views refer to: Oracle9i SQL Reference, “CREATE MATERIALIZED VIEW / SNAPSHOT.”
  • #11: Retrieving Data from a View You can retrieve data from a view as you would from any table. You can display either the contents of the entire view or just specific rows and columns.
  • #12: Views in the Data Dictionary
  • #13: Modifying a View With the OR REPLACE option, a view can be created even if one exists with this name already, thus replacing the old version of the view for its owner. This means that the view can be altered without dropping, re-creating, and regranting object privileges. Note: When assigning column aliases in the CREATE VIEW clause, remember that the aliases are listed in the same order as the columns in the subquery. Instructor Note The OR REPLACE option started with Oracle7. With earlier versions of Oracle, if the view needed to be changed, it had to be dropped and re-created. Demo: 11_emp.sql Purpose: To illustrate creating a view using aliases
  • #14: Creating a Complex View The example on the slide creates a complex view of department names, minimum salaries, maximum salaries, and average salaries by department. Note that alternative names have been specified for the view. This is a requirement if any column of the view is derived from a function or an expression. You can view the structure of the view by using the iSQL*Plus DESCRIBE command. Display the contents of the view by issuing a SELECT statement. SELECT * FROM dept_sum_vu;
  • #15: Performing DML Operations on a View You can perform DML operations on data through a view if those operations follow certain rules. You can remove a row from a view unless it contains any of the following: Group functions A GROUP BY clause The DISTINCT keyword The pseudocolumn ROWNUM keyword Instructor Note For each row returned by a query, the ROWNUM pseudocolumn returns a number indicating the order in which Oracle server selects the row from a table or set of joined rows. The first row selected has a ROWNUM of 1, the second has 2, and so on.
  • #16: Performing DML Operations on a View (continued) You can modify data through a view unless it contains any of the conditions mentioned in the previous slide or columns defined by expressions—for example, SALARY * 12.
  • #17: Performing DML Operations on a View (continued) You can add data through a view unless it contains any of the items listed in the slide or there are NOT NULL columns without default values in the base table that are not selected by the view. All required values must be present in the view. Remember that you are adding values directly into the underlying table through the view. For more information, see 0racle9i SQL Reference, “CREATE VIEW.” Instructor Note With Oracle7.3 and later, you can modify views that involve joins with some restrictions. The restrictions for DML operations described in the slide also apply to join views. Any UPDATE, INSERT, or DELETE statement on a join view can modify only one underlying base table. If at least one column in the subquery join has a unique index, then it may be possible to modify one base table in a join view. You can query USER_UPDATABLE_COLUMNS to see whether the columns in a join view can be updated.
  • #18: Using the WITH CHECK OPTION Clause It is possible to perform referential integrity checks through views. You can also enforce constraints at the database level. The view can be used to protect data integrity, but the use is very limited. The WITH CHECK OPTION clause specifies that INSERTs and UPDATEs performed through the view cannot create rows which the view cannot select, and therefore it allows integrity constraints and data validation checks to be enforced on data being inserted or updated. If there is an attempt to perform DML operations on rows that the view has not selected, an error is displayed, with the constraint name if that has been specified. UPDATE empvu20 SET department_id = 10 WHERE employee_id = 201; UPDATE empvu20 * ERROR at line 1: ORA-01402: view WITH CHECK OPTION where-clause violation Note: No rows are updated because if the department number were to change to 10, the view would no longer be able to see that employee. Therefore, with the WITH CHECK OPTION clause, the view can see only employees in department 20 and does not allow the department number for those employees to be changed through the view.
  • #19: Denying DML Operations You can ensure that no DML operations occur on your view by creating it with the WITH READ ONLY option. The example on the slide modifies the EMPVU10 view to prevent any DML operations on the view. Instructor Note (for page 11-17) If the user does not supply a constraint name, the system assigns a name in the form SYS_Cn, where n is an integer that makes the constraint name unique within the system.
  • #20: Denying DML Operations Any attempts to remove a row from a view with a read-only constraint results in an error. DELETE FROM empvu10 WHERE employee_number = 200; DELETE FROM empvu10 * ERROR at line 1: ORA-01752: cannot delete from view without exactly one key- preserved table Any attempt to insert a row or modify a row using the view with a read-only constraint results in Oracle server error: 01733: virtual column not allowed here.
  • #21: Removing a View You use the DROP VIEW statement to remove a view. The statement removes the view definition from the database. Dropping views has no effect on the tables on which the view was based. Views or other applications based on deleted views become invalid. Only the creator or a user with the DROP ANY VIEW privilege can remove a view. In the syntax: viewis the name of the view
  • #22: Inline Views An inline view is created by placing a subquery in the FROM clause and giving that subquery an alias. The subquery defines a data source that can be referenced in the main query. In the following example, the inline view b returns the details of all department numbers and the maximum salary for each department from the EMPLOYEES table. The WHERE a.department_id = b.department_id AND a.salary &amp;lt; b.maxsal clause of the main query displays employee names, salaries, department numbers, and maximum salaries for all the employees who earn less than the maximum salary in their department. SELECT a.last_name, a.salary, a.department_id, b.maxsal FROM employees a, (SELECT department_id, max(salary) maxsal FROM employees GROUP BY department_id) b WHERE a.department_id = b.department_id AND a.salary &amp;lt; b.maxsal;
  • #23: “Top-N” Analysis Top-N queries are useful in scenarios where the need is to display only the n top-most or the n bottom-most records from a table based on a condition. This result set can be used for further analysis. For example, using Top-N analysis you can perform the following types of queries: The top three earners in the company The four most recent recruits in the company The top two sales representatives who have sold the maximum number of products The top three products that have had the maximum sales in the last six months Instructor Note The capability to include the ORDER BY clause in a subquery makes Top-N analysis possible.
  • #24: Performing “Top-N” Analysis Top-N queries use a consistent nested query structure with the elements described below: A subquery or an inline view to generate the sorted list of data. The subquery or the inline view includes the ORDER BY clause to ensure that the ranking is in the desired order. For results retrieving the largest values, a DESC parameter is needed. An outer query to limit the number of rows in the final result set. The outer query includes the following components: The ROWNUM pseudocolumn, which assigns a sequential value starting with 1 to each of the rows returned from the subquery. A WHERE clause, which specifies the n rows to be returned. The outer WHERE clause must use a &amp;lt; or &amp;lt;= operator.
  • #25: Example of “Top-N” Analysis The example on the slide illustrates how to display the names and salaries of the top three earners from the EMPLOYEES table. The subquery returns the details of all employee names and salaries from the EMPLOYEES table, sorted in the descending order of the salaries. The WHERE ROWNUM &amp;lt; 3 clause of the main query ensures that only the first three records from this result set are displayed. Here is another example of Top-N analysis that uses an inline view. The example below uses the inline view E to display the four most senior employees in the company. SELECT ROWNUM as SENIOR,E.last_name, E.hire_date FROM (SELECT last_name,hire_date FROM employees ORDER BY hire_date)E WHERE rownum &amp;lt;= 4;
  • #26: What Is a View? A view is based on a table or another view and acts as a window through which data on tables can be viewed or changed. A view does not contain data. The definition of the view is stored in the data dictionary. You can see the definition of the view in the USER_VIEWS data dictionary table. Advantages of Views Restrict database access Simplify queries Provide data independence Provide multiple views of the same data Can be removed without affecting the underlying data View Options Can be a simple view, based on one table Can be a complex view based on more than one table or can contain groups of functions Can replace other views with the same name Can contain a check constraint Can be read-only
  • #27: Practice 11 Overview In this practice, you create simple and complex views and attempt to perform DML statements on the views.
  • #28: Practice 11 1.Create a view called EMPLOYEES_VU based on the employee numbers, employee names, anddepartment numbers from the EMPLOYEES table. Change the heading for the employee name toEMPLOYEE. 2.Display the contents of the EMPLOYEES_VU view. 3.Select the view name and text from the USER_VIEWS data dictionary view. Note: Another view already exists. The EMP_DETAILS_VIEW was created as part of your schema. Note: To see more contents of a LONG column, use the iSQL*Plus command SET LONG n, where n is the value of the number of characters of the LONG column that you want to see. 4.Using your EMPLOYEES_VU view, enter a query to display all employee names and department numbers.
  • #29: Practice 11 (continued) 5.Create a view named DEPT50 that contains the employee numbers, employee last names, anddepartment numbers for all employees in department 50. Label the view columnsEMPNO, EMPLOYEE, and DEPTNO. Do not allow an employee to be reassigned to another department through the view. 6.Display the structure and contents of the DEPT50 view. 7.Attempt to reassign Matos to department 80. If you have time, complete the following exercise: 8.Create a view called SALARY_VU based on the employee last names, department names, salaries, and salary grades for all employees. Use the EMPLOYEES, DEPARTMENTS, and JOB_GRADES tables. Label the columns Employee, Department, Salary, and Grade, respectively.