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

What's hot

07 Using Oracle-Supported Package in Application Development
07 Using Oracle-Supported Package in Application Development07 Using Oracle-Supported Package in Application Development
07 Using Oracle-Supported Package in Application Development
rehaniltifat
 
Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Including Constraints -Oracle Data base
Including Constraints -Oracle Data base
Salman Memon
 
Writing Basic SQL SELECT Statements
Writing Basic SQL SELECT StatementsWriting Basic SQL SELECT Statements
Writing Basic SQL SELECT Statements
Salman Memon
 
Les02 (restricting and sorting data)
Les02 (restricting and sorting data)Les02 (restricting and sorting data)
Les02 (restricting and sorting data)Achmad Solichin
 
08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadata08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadata
rehaniltifat
 
Oracle SQL Basics
Oracle SQL BasicsOracle SQL Basics
Oracle SQL Basics
Dhananjay Goel
 
SQL - DML and DDL Commands
SQL - DML and DDL CommandsSQL - DML and DDL Commands
SQL - DML and DDL Commands
Shrija Madhu
 
Oraclesql
OraclesqlOraclesql
Oraclesql
Priya Goyal
 
Manipulating Data Oracle Data base
Manipulating Data Oracle Data baseManipulating Data Oracle Data base
Manipulating Data Oracle Data base
Salman Memon
 
Sql oracle
Sql oracleSql oracle
Sql oracle
Md.Abu Noman Shuvo
 
11 Understanding and Influencing the PL/SQL Compilar
11 Understanding and Influencing the PL/SQL Compilar11 Understanding and Influencing the PL/SQL Compilar
11 Understanding and Influencing the PL/SQL Compilar
rehaniltifat
 
1 - Introduction to PL/SQL
1 - Introduction to PL/SQL1 - Introduction to PL/SQL
1 - Introduction to PL/SQL
rehaniltifat
 
Creating and Managing Tables -Oracle Data base
Creating and Managing Tables -Oracle Data base Creating and Managing Tables -Oracle Data base
Creating and Managing Tables -Oracle Data base
Salman Memon
 
Les08 (manipulating data)
Les08 (manipulating data)Les08 (manipulating data)
Les08 (manipulating data)
Achmad Solichin
 
Sql – Structured Query Language
Sql – Structured Query LanguageSql – Structured Query Language
Sql – Structured Query Languagepandey3045_bit
 
Oracle basic queries
Oracle basic queriesOracle basic queries
Oracle basic queries
PRAKHAR JHA
 
Sql server T-sql basics ppt-3
Sql server T-sql basics  ppt-3Sql server T-sql basics  ppt-3
Sql server T-sql basics ppt-3
Vibrant Technologies & Computers
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
Tayyab Hussain
 
Restricting and Sorting Data - Oracle Data Base
Restricting and Sorting Data - Oracle Data BaseRestricting and Sorting Data - Oracle Data Base
Restricting and Sorting Data - Oracle Data Base
Salman Memon
 

What's hot (20)

07 Using Oracle-Supported Package in Application Development
07 Using Oracle-Supported Package in Application Development07 Using Oracle-Supported Package in Application Development
07 Using Oracle-Supported Package in Application Development
 
Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Including Constraints -Oracle Data base
Including Constraints -Oracle Data base
 
Writing Basic SQL SELECT Statements
Writing Basic SQL SELECT StatementsWriting Basic SQL SELECT Statements
Writing Basic SQL SELECT Statements
 
Les02 (restricting and sorting data)
Les02 (restricting and sorting data)Les02 (restricting and sorting data)
Les02 (restricting and sorting data)
 
Sql select
Sql select Sql select
Sql select
 
08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadata08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadata
 
Oracle SQL Basics
Oracle SQL BasicsOracle SQL Basics
Oracle SQL Basics
 
SQL - DML and DDL Commands
SQL - DML and DDL CommandsSQL - DML and DDL Commands
SQL - DML and DDL Commands
 
Oraclesql
OraclesqlOraclesql
Oraclesql
 
Manipulating Data Oracle Data base
Manipulating Data Oracle Data baseManipulating Data Oracle Data base
Manipulating Data Oracle Data base
 
Sql oracle
Sql oracleSql oracle
Sql oracle
 
11 Understanding and Influencing the PL/SQL Compilar
11 Understanding and Influencing the PL/SQL Compilar11 Understanding and Influencing the PL/SQL Compilar
11 Understanding and Influencing the PL/SQL Compilar
 
1 - Introduction to PL/SQL
1 - Introduction to PL/SQL1 - Introduction to PL/SQL
1 - Introduction to PL/SQL
 
Creating and Managing Tables -Oracle Data base
Creating and Managing Tables -Oracle Data base Creating and Managing Tables -Oracle Data base
Creating and Managing Tables -Oracle Data base
 
Les08 (manipulating data)
Les08 (manipulating data)Les08 (manipulating data)
Les08 (manipulating data)
 
Sql – Structured Query Language
Sql – Structured Query LanguageSql – Structured Query Language
Sql – Structured Query Language
 
Oracle basic queries
Oracle basic queriesOracle basic queries
Oracle basic queries
 
Sql server T-sql basics ppt-3
Sql server T-sql basics  ppt-3Sql server T-sql basics  ppt-3
Sql server T-sql basics ppt-3
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
 
Restricting and Sorting Data - Oracle Data Base
Restricting and Sorting Data - Oracle Data BaseRestricting and Sorting Data - Oracle Data Base
Restricting and Sorting Data - Oracle Data Base
 

Viewers also liked

Views Oracle Database
Views Oracle DatabaseViews Oracle Database
Views Oracle Database
Wagner Almeida
 
A New View of Database Views
A New View of Database ViewsA New View of Database Views
A New View of Database Views
Michael Rosenblum
 
Sql queires
Sql queiresSql queires
Sql queires
MohitKumar1985
 
Dbms lab questions
Dbms lab questionsDbms lab questions
Dbms lab questions
Parthipan Parthi
 
A must Sql notes for beginners
A must Sql notes for beginnersA must Sql notes for beginners
A must Sql notes for beginners
Ram Sagar Mourya
 
Sql queries with answers
Sql queries with answersSql queries with answers
Sql queries with answers
vijaybusu
 

Viewers also liked (8)

Sql wksht-5
Sql wksht-5Sql wksht-5
Sql wksht-5
 
Views Oracle Database
Views Oracle DatabaseViews Oracle Database
Views Oracle Database
 
A New View of Database Views
A New View of Database ViewsA New View of Database Views
A New View of Database Views
 
SQL BASIC QUERIES SOLUTION ~hmftj
SQL BASIC QUERIES SOLUTION ~hmftjSQL BASIC QUERIES SOLUTION ~hmftj
SQL BASIC QUERIES SOLUTION ~hmftj
 
Sql queires
Sql queiresSql queires
Sql queires
 
Dbms lab questions
Dbms lab questionsDbms lab questions
Dbms lab questions
 
A must Sql notes for beginners
A must Sql notes for beginnersA must Sql notes for beginners
A must Sql notes for beginners
 
Sql queries with answers
Sql queries with answersSql queries with answers
Sql queries with answers
 

Similar to Creating Views - oracle database

Les11.ppt
Les11.pptLes11.ppt
Sql views
Sql viewsSql views
Sql views
arshid045
 
Lesson10
Lesson10Lesson10
Lesson10renguzi
 
Les12[1]Creating Views
Les12[1]Creating ViewsLes12[1]Creating Views
Les12[1]Creating Views
siavosh kaviani
 
Creating other schema objects
Creating other schema objectsCreating other schema objects
Creating other schema objects
Syed Zaid Irshad
 
Les10
Les10Les10
Oracle views
Oracle viewsOracle views
Oracle views
Balqees Al.Mubarak
 
e computer notes - Creating views
e computer notes - Creating viewse computer notes - Creating views
e computer notes - Creating viewsecomputernotes
 
Les09.ppt
Les09.pptLes09.ppt
Oracle Data Redaction
Oracle Data RedactionOracle Data Redaction
Oracle Data Redaction
Alex Zaballa
 
Data Redaction - OTN TOUR LA 2015
Data Redaction - OTN TOUR LA 2015 Data Redaction - OTN TOUR LA 2015
Data Redaction - OTN TOUR LA 2015
Alex Zaballa
 
Aggregating Data Using Group Functions
Aggregating Data Using Group FunctionsAggregating Data Using Group Functions
Aggregating Data Using Group Functions
Salman Memon
 
Useful PL/SQL Supplied Packages
Useful PL/SQL Supplied PackagesUseful PL/SQL Supplied Packages
Useful PL/SQL Supplied Packages
Maria Colgan
 
Oracle SQL - Aggregating Data Les 05.ppt
Oracle SQL - Aggregating Data Les 05.pptOracle SQL - Aggregating Data Les 05.ppt
Oracle SQL - Aggregating Data Les 05.ppt
DrZeeshanBhatti
 
Sql ch 13 - sql-views
Sql ch 13 - sql-viewsSql ch 13 - sql-views
Sql ch 13 - sql-views
Mukesh Tekwani
 
Les13[1]Other Database Objects
Les13[1]Other Database ObjectsLes13[1]Other Database Objects
Les13[1]Other Database Objects
siavosh kaviani
 

Similar to Creating Views - oracle database (20)

Les11.ppt
Les11.pptLes11.ppt
Les11.ppt
 
Sql views
Sql viewsSql views
Sql views
 
Les11
Les11Les11
Les11
 
Lesson10
Lesson10Lesson10
Lesson10
 
Les12[1]Creating Views
Les12[1]Creating ViewsLes12[1]Creating Views
Les12[1]Creating Views
 
Les10
Les10Les10
Les10
 
Creating other schema objects
Creating other schema objectsCreating other schema objects
Creating other schema objects
 
Les10
Les10Les10
Les10
 
Oracle views
Oracle viewsOracle views
Oracle views
 
e computer notes - Creating views
e computer notes - Creating viewse computer notes - Creating views
e computer notes - Creating views
 
Les09.ppt
Les09.pptLes09.ppt
Les09.ppt
 
Oracle Data Redaction
Oracle Data RedactionOracle Data Redaction
Oracle Data Redaction
 
Data Redaction - OTN TOUR LA 2015
Data Redaction - OTN TOUR LA 2015 Data Redaction - OTN TOUR LA 2015
Data Redaction - OTN TOUR LA 2015
 
Aggregating Data Using Group Functions
Aggregating Data Using Group FunctionsAggregating Data Using Group Functions
Aggregating Data Using Group Functions
 
Les12 creating views
Les12 creating viewsLes12 creating views
Les12 creating views
 
Useful PL/SQL Supplied Packages
Useful PL/SQL Supplied PackagesUseful PL/SQL Supplied Packages
Useful PL/SQL Supplied Packages
 
Oracle SQL - Aggregating Data Les 05.ppt
Oracle SQL - Aggregating Data Les 05.pptOracle SQL - Aggregating Data Les 05.ppt
Oracle SQL - Aggregating Data Les 05.ppt
 
Les09
Les09Les09
Les09
 
Sql ch 13 - sql-views
Sql ch 13 - sql-viewsSql ch 13 - sql-views
Sql ch 13 - sql-views
 
Les13[1]Other Database Objects
Les13[1]Other Database ObjectsLes13[1]Other Database Objects
Les13[1]Other Database Objects
 

More from Salman Memon

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

More from Salman Memon (20)

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

Recently uploaded

Exploring Montreal's Artistic Heritage Top Art Galleries and Museums to Visit
Exploring Montreal's Artistic Heritage Top Art Galleries and Museums to VisitExploring Montreal's Artistic Heritage Top Art Galleries and Museums to Visit
Exploring Montreal's Artistic Heritage Top Art Galleries and Museums to Visit
Spade & Palacio Tours
 
Understanding the Running Costs of Electric Scooters.pptx
Understanding the Running Costs of Electric Scooters.pptxUnderstanding the Running Costs of Electric Scooters.pptx
Understanding the Running Costs of Electric Scooters.pptx
Zivah ElectriVa Private Limited
 
Uk Visa Complete Guide and application process
Uk Visa Complete Guide and application processUk Visa Complete Guide and application process
Uk Visa Complete Guide and application process
pandeypratikwgblindi
 
How To Talk To a Live Person at American Airlines
How To Talk To a Live Person at American AirlinesHow To Talk To a Live Person at American Airlines
How To Talk To a Live Person at American Airlines
flyn goo
 
How To Change Name On Volaris Ticket.pdf
How To Change Name On Volaris Ticket.pdfHow To Change Name On Volaris Ticket.pdf
How To Change Name On Volaris Ticket.pdf
namechange763
 
Exploring Heritage The Ultimate Cultural Tour in Palmer, Puerto Rico
Exploring Heritage The Ultimate Cultural Tour in Palmer, Puerto RicoExploring Heritage The Ultimate Cultural Tour in Palmer, Puerto Rico
Exploring Heritage The Ultimate Cultural Tour in Palmer, Puerto Rico
Caribbean Breeze Adventures
 
MC INTERNATIONALS | TRAVEL COMPANY IN JHANG
MC INTERNATIONALS | TRAVEL COMPANY IN JHANGMC INTERNATIONALS | TRAVEL COMPANY IN JHANG
MC INTERNATIONALS | TRAVEL COMPANY IN JHANG
AshBhatt4
 
Jose RIZAL History and his travel Paris to berlin
Jose RIZAL History and his travel Paris to berlinJose RIZAL History and his travel Paris to berlin
Jose RIZAL History and his travel Paris to berlin
MaryGraceArdalesLope
 
TOP 10 Historic Places To See in Kuruskhetra.
TOP 10 Historic Places To See in Kuruskhetra.TOP 10 Historic Places To See in Kuruskhetra.
TOP 10 Historic Places To See in Kuruskhetra.
ujjwalsethi113
 
Hunza Cherry Blossom tour 2025- Hunza Adventure Tours
Hunza Cherry Blossom tour 2025- Hunza Adventure ToursHunza Cherry Blossom tour 2025- Hunza Adventure Tours
Hunza Cherry Blossom tour 2025- Hunza Adventure Tours
Hunza Adventure Tours
 
欧洲杯开户-信誉的欧洲杯开户-正规欧洲杯开户|【​网址​🎉ac123.net🎉​】
欧洲杯开户-信誉的欧洲杯开户-正规欧洲杯开户|【​网址​🎉ac123.net🎉​】欧洲杯开户-信誉的欧洲杯开户-正规欧洲杯开户|【​网址​🎉ac123.net🎉​】
欧洲杯开户-信誉的欧洲杯开户-正规欧洲杯开户|【​网址​🎉ac123.net🎉​】
bljeremy734
 
4 DAYS MASAI MARA WILDEBEEST MIGRATION SAFARI TOUR PACKAGE KENYA
4 DAYS MASAI MARA WILDEBEEST MIGRATION SAFARI TOUR PACKAGE KENYA4 DAYS MASAI MARA WILDEBEEST MIGRATION SAFARI TOUR PACKAGE KENYA
4 DAYS MASAI MARA WILDEBEEST MIGRATION SAFARI TOUR PACKAGE KENYA
Bush Troop Safari
 
Paddle, Float, and Explore The Ultimate River Tour Experience in Monitor, WA
Paddle, Float, and Explore The Ultimate River Tour Experience in Monitor, WAPaddle, Float, and Explore The Ultimate River Tour Experience in Monitor, WA
Paddle, Float, and Explore The Ultimate River Tour Experience in Monitor, WA
River Recreation - Washington Whitewater Rafting
 
Agence Régionale du Tourisme Grand Est - brochure MICE 2024.pdf
Agence Régionale du Tourisme Grand Est - brochure MICE 2024.pdfAgence Régionale du Tourisme Grand Est - brochure MICE 2024.pdf
Agence Régionale du Tourisme Grand Est - brochure MICE 2024.pdf
MICEboard
 
Winter Festivities in Italy
Winter Festivities in ItalyWinter Festivities in Italy
Winter Festivities in Italy
Time for Sicily
 
Get tailored experience with Stonehenge tours from London
Get tailored experience with Stonehenge tours from LondonGet tailored experience with Stonehenge tours from London
Get tailored experience with Stonehenge tours from London
London Country Tours
 
Antarctica- Icy wilderness of extremes and wonder
Antarctica- Icy wilderness of extremes and wonderAntarctica- Icy wilderness of extremes and wonder
Antarctica- Icy wilderness of extremes and wonder
tahreemzahra82
 
LUXURY TRAVEL THE ULTIMATE TOKYO EXPERIENCE FROM SINGAPORE.pdf
LUXURY TRAVEL THE ULTIMATE TOKYO EXPERIENCE FROM SINGAPORE.pdfLUXURY TRAVEL THE ULTIMATE TOKYO EXPERIENCE FROM SINGAPORE.pdf
LUXURY TRAVEL THE ULTIMATE TOKYO EXPERIENCE FROM SINGAPORE.pdf
Diper Tour
 
The Power of a Glamping Go-To-Market Accelerator Plan.pptx
The Power of a Glamping Go-To-Market Accelerator Plan.pptxThe Power of a Glamping Go-To-Market Accelerator Plan.pptx
The Power of a Glamping Go-To-Market Accelerator Plan.pptx
RezStream
 

Recently uploaded (19)

Exploring Montreal's Artistic Heritage Top Art Galleries and Museums to Visit
Exploring Montreal's Artistic Heritage Top Art Galleries and Museums to VisitExploring Montreal's Artistic Heritage Top Art Galleries and Museums to Visit
Exploring Montreal's Artistic Heritage Top Art Galleries and Museums to Visit
 
Understanding the Running Costs of Electric Scooters.pptx
Understanding the Running Costs of Electric Scooters.pptxUnderstanding the Running Costs of Electric Scooters.pptx
Understanding the Running Costs of Electric Scooters.pptx
 
Uk Visa Complete Guide and application process
Uk Visa Complete Guide and application processUk Visa Complete Guide and application process
Uk Visa Complete Guide and application process
 
How To Talk To a Live Person at American Airlines
How To Talk To a Live Person at American AirlinesHow To Talk To a Live Person at American Airlines
How To Talk To a Live Person at American Airlines
 
How To Change Name On Volaris Ticket.pdf
How To Change Name On Volaris Ticket.pdfHow To Change Name On Volaris Ticket.pdf
How To Change Name On Volaris Ticket.pdf
 
Exploring Heritage The Ultimate Cultural Tour in Palmer, Puerto Rico
Exploring Heritage The Ultimate Cultural Tour in Palmer, Puerto RicoExploring Heritage The Ultimate Cultural Tour in Palmer, Puerto Rico
Exploring Heritage The Ultimate Cultural Tour in Palmer, Puerto Rico
 
MC INTERNATIONALS | TRAVEL COMPANY IN JHANG
MC INTERNATIONALS | TRAVEL COMPANY IN JHANGMC INTERNATIONALS | TRAVEL COMPANY IN JHANG
MC INTERNATIONALS | TRAVEL COMPANY IN JHANG
 
Jose RIZAL History and his travel Paris to berlin
Jose RIZAL History and his travel Paris to berlinJose RIZAL History and his travel Paris to berlin
Jose RIZAL History and his travel Paris to berlin
 
TOP 10 Historic Places To See in Kuruskhetra.
TOP 10 Historic Places To See in Kuruskhetra.TOP 10 Historic Places To See in Kuruskhetra.
TOP 10 Historic Places To See in Kuruskhetra.
 
Hunza Cherry Blossom tour 2025- Hunza Adventure Tours
Hunza Cherry Blossom tour 2025- Hunza Adventure ToursHunza Cherry Blossom tour 2025- Hunza Adventure Tours
Hunza Cherry Blossom tour 2025- Hunza Adventure Tours
 
欧洲杯开户-信誉的欧洲杯开户-正规欧洲杯开户|【​网址​🎉ac123.net🎉​】
欧洲杯开户-信誉的欧洲杯开户-正规欧洲杯开户|【​网址​🎉ac123.net🎉​】欧洲杯开户-信誉的欧洲杯开户-正规欧洲杯开户|【​网址​🎉ac123.net🎉​】
欧洲杯开户-信誉的欧洲杯开户-正规欧洲杯开户|【​网址​🎉ac123.net🎉​】
 
4 DAYS MASAI MARA WILDEBEEST MIGRATION SAFARI TOUR PACKAGE KENYA
4 DAYS MASAI MARA WILDEBEEST MIGRATION SAFARI TOUR PACKAGE KENYA4 DAYS MASAI MARA WILDEBEEST MIGRATION SAFARI TOUR PACKAGE KENYA
4 DAYS MASAI MARA WILDEBEEST MIGRATION SAFARI TOUR PACKAGE KENYA
 
Paddle, Float, and Explore The Ultimate River Tour Experience in Monitor, WA
Paddle, Float, and Explore The Ultimate River Tour Experience in Monitor, WAPaddle, Float, and Explore The Ultimate River Tour Experience in Monitor, WA
Paddle, Float, and Explore The Ultimate River Tour Experience in Monitor, WA
 
Agence Régionale du Tourisme Grand Est - brochure MICE 2024.pdf
Agence Régionale du Tourisme Grand Est - brochure MICE 2024.pdfAgence Régionale du Tourisme Grand Est - brochure MICE 2024.pdf
Agence Régionale du Tourisme Grand Est - brochure MICE 2024.pdf
 
Winter Festivities in Italy
Winter Festivities in ItalyWinter Festivities in Italy
Winter Festivities in Italy
 
Get tailored experience with Stonehenge tours from London
Get tailored experience with Stonehenge tours from LondonGet tailored experience with Stonehenge tours from London
Get tailored experience with Stonehenge tours from London
 
Antarctica- Icy wilderness of extremes and wonder
Antarctica- Icy wilderness of extremes and wonderAntarctica- Icy wilderness of extremes and wonder
Antarctica- Icy wilderness of extremes and wonder
 
LUXURY TRAVEL THE ULTIMATE TOKYO EXPERIENCE FROM SINGAPORE.pdf
LUXURY TRAVEL THE ULTIMATE TOKYO EXPERIENCE FROM SINGAPORE.pdfLUXURY TRAVEL THE ULTIMATE TOKYO EXPERIENCE FROM SINGAPORE.pdf
LUXURY TRAVEL THE ULTIMATE TOKYO EXPERIENCE FROM SINGAPORE.pdf
 
The Power of a Glamping Go-To-Market Accelerator Plan.pptx
The Power of a Glamping Go-To-Market Accelerator Plan.pptxThe Power of a Glamping Go-To-Market Accelerator Plan.pptx
The Power of a Glamping Go-To-Market Accelerator Plan.pptx
 

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

  1. Schedule:TimingTopic 20 minutesLecture 20 minutesPractice 40 minutesTotal
  2. 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.
  3. 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;
  4. 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.”
  5. 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
  6. 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
  7. 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.
  8. 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.”
  9. 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.
  10. Views in the Data Dictionary
  11. 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
  12. 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;
  13. 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.
  14. 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.
  15. 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.
  16. 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.
  17. 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.
  18. 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.
  19. 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
  20. 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;
  21. “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.
  22. 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.
  23. 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;
  24. 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
  25. Practice 11 Overview In this practice, you create simple and complex views and attempt to perform DML statements on the views.
  26. 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.
  27. 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.