Database Programming Sections 11 & 12 – Creating, and Managing Views, Sequences, Indexes, and...
-
Upload
roberta-harvey -
Category
Documents
-
view
243 -
download
1
Transcript of Database Programming Sections 11 & 12 – Creating, and Managing Views, Sequences, Indexes, and...
Database Programming
Sections 11 & 12 – Creating, and Managing Views, Sequences, Indexes, and Synonymns
Marge Hohly 2
What is a View? A view is a query stored as a SELECT
statement in the data dictionary. A table of logical subsets or combinations of data based on a table or another view.
A ”window” into the database for convenience/per/permission
Presents data from one or more tables in one place
Two Types of Views Simple Complex
Marge Hohly 3
Example of a View CREATE VIEW
view_employees AS SELECT first_name, last_name, emailFROM employeesWHERE employee_id BETWEEN 100 and 124;
SELECT * FROM view_employees;
Marge Hohly 4
Guidelines for Creating a View The subquery that defines the view can
contain complex SELECT syntax The subquery that defines the view cannot
contain an ORDER BY clause You can use the OR REPLACE option to
change the definition of the view without having to drop or re-grant object privileges previously granted
Aliases can be used for the column names in the subquery
Marge Hohly 5
Aliases in a View Column names in the SELECT statement can have aliases
as shown below. Note that aliases can also be listed after the CREATE VIEW statement and before the SELECT subquery
CREATE VIEW view_copy_d_cdsAS SELECT cd_number AS “Number”, title AS “Title”, year AS “Year Recorded” FROM d_cds;
CREATE VIEW view_copy_d_cds(Number, Title, Year Recorded)AS SELECT cd_number, title, yearFROM d_cds;
Marge Hohly 6
The Syntax For Creating a View CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view_name [(alias
[,alias]....)]AS subquery[WITH CHECK OPTION [CONSTRAINT constraint_name]][WITH READ ONLY [CONSTRAINT constraint_name]];
OR REPLACE – recreates the view if it already exists FORCE – creates the view regardless of whether or not the base tables exist NO FORCE – creates the view only if the base tables exist (DEFAULT) view_name – name of the view alias – specifies a name of each expression selected by the view’s query subquery – a complete SELECT statement (you can use aliases for the
columns in the SELECT list) WITH CHECK OPTION – specifies that only rows accessible to the view can
be inserted or updated WITH READ ONLY – ensures that NO DML operations can be performed on
this view
Marge Hohly 7
Simple vs. Complex
Feature Simple View Complex View
Number of tables used to derive data
One One or more
Can contain functions
No Yes
Can contain groups of data
No Yes
Can perform DML operations through a view
Yes Not always
Marge Hohly 8
Simple View Example
CREATE VIEW view_copy_d_cds(“CD Number”, Title, “Year Recorded”)AS SELECT cd_number, title, yearFROM copy_d_cds;
Marge Hohly 9
Complex View Example CREATE VIEW view_dj_on_demand
(LAST_NAME, PHONE, EVENT, DATE_HELD) AS SELECT c.last_name, c.phone, e.name, TO_CHAR(e.event_date, ‘Month dd, YYYY’)FROM d_clients c, d_events eWHERE c.client_number = e.client_number;
Marge Hohly 10
Modifying a View To modify a view, use the [OR
REPLACE] option The old view will be replaced by the
new version CREATE OR REPLACE VIEW
view_copy_d_cdsAS SELECT cd_number, producer, title, yearFROM copy_d_cds;
Marge Hohly 11
DML Operations on a View DML operations (INSERT, UPDATE,
and DELETE) can be performed on a simple view
Data in the underlying base tables can be changed also
To prevent unintended changes, the DBA can control data access using the WITH CHECK OPTION and WITH READ ONLY constraints
Marge Hohly 12
WITH CHECK OPTION CONSTRAINT CREATE OR REPLACE VIEW view_dept50 AS
SELECT department_id, employee_id, first_name, last_name, salaryFROM employeesWHERE department_id = 50WITH CHECK OPTION CONSTRAINT view_dept50_check;
UPDATE view_dept50SET department_id = 190WHERE employee_id = 141;NOTE: ORA-01402: view WITH CHECK OPTION where-clause violation
Marge Hohly 13
WITH READ ONLY CONSTRAINT CREATE OR REPLACE VIEW view_dept50 AS
SELECT department_id, employee_id, first_name, last_name, salaryFROM employeesWHERE department_id = 50WITH READ ONLY CONSTRAINT view_dept50_read;
DELETE FROM view_dept50WHERE employee_id = 144;ORA-01752: cannot delete from view without exactly one key-preserved table
Marge Hohly 14
DML Restrictions on a View You cannot REMOVE a row from an
underlying base table if the view contains any of the following: Group functions A GROUP BY clause The pseudocolumn ROWNUM keyword
ROWNUM is just a number value given to each row in the result set. For each row returned by a query, the ROWNUM pseudocolumn returns a number indicating the order in which Oracle 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.
You can use ROWNUM to limit the number of rows returned by a query, as in this example:SELECT * FROM employees WHERE ROWNUM < 10;
Marge Hohly 15
DML Restrictions on a View You cannot MODIFY data through a view
if the view contains: Group functions A GROUP BY clause The pseudocolumn ROWNUM keyword The DISTINCT keyword Columns defined by expressions
Marge Hohly 16
DML Restrictions on a VIEW You cannot ADD data through a view if the
view includes group functions includes a GROUP BY clause includes the pseudocolumn ROWNUM keyword includes the DISTINCT keyword includes columns defined by expressions does not include NOT NULL columns in the base
tables – the user of the view must know which column in the base table are NOT NULL – these columns must be in the view.
Marge Hohly 17
Deleting a View
DROP VIEW viewname;
Removing a view does not effect the data in the underlying tables
If the view was used to manipulate data in the past, these changes to the base tables remain
Only the creator or users with the DROP ANY VIEW privilege can remove a view
Marge Hohly 18
What is an Inline View? Also known as queries in the FROM
clause The view is created “on the fly” instead
of saving the view as a separate object A common use for in-line views in Oracle
SQL is the simplify complex queries by removing join operations and condensing several separate queries into a single query.
Marge Hohly 19
Inline View Example SELECT e.name, e.description,
p.maxrange, p.codeFROM d_events e, (SELECT code, max(high_range) maxrange FROM d_packages GROUP BY code) pWHERE e.package_code = p.codeAND e.cost < p.maxrange;
The data returned by the subquery is given an alias, which is then used in conjunction with the main query to return selected columns from both query sources.
Marge Hohly 20
Inline View Example SELECT code, max(high_range) maxrange
FROM d_packagesGROUP BY code;
Marge Hohly 21
Top-N Analysis A SQL operation used to rank results Add a pseudocolumn called ROWNUM ROWNUM is used to select the top “n”
(number) of rows
SELECT ROWNUM as top, name, costFROM (SELECT name, cost FROM d_events ORDER BY cost DESC)WHERE ROWNUM <= 2;
Marge Hohly 22
The Syntax for Creating a Sequence CREATE SEQUENCE sequence_name
[INCREMENT BY n][START WITH n][{MAXVALUE n | NOMAXVALUE}][{MINVALUE n | NOMINVALUE}][{CYCLE | NOCYCLE}][{CACHE n | NOCACHE}];
Sequence_name – the name of sequence generator (object) INCREMENT BY n – interval between sequence numbers where n is an integer (if omitted n is 1) START WITH n – specifies the first sequence number to be generated (if omitted start with 1) MAXVALUE n – specifies the maximum value the sequence can generate NOMAXVALUE – specifies a maximum value of 10^27 for ascending and -1 for descending MINVALUE n – specifies the minimum value the sequence can generate NOMINVALUE – specifies a minimum value of 1 for ascending and -10^27 for descending CYCLE – whether the sequence continues to generate values after reaching its max or min value NOCYCLE – the default if CYCLE is not specified CACHE n – specifies how many values the Oracle Server preallocates and keeps in memory
(default is 20) if the sequence values are cached, they will be lost if there is a system failure NOCACHE – does not cache any values
Marge Hohly 23
Example of a Sequence CREATE SEQUENCE emp_emp_id_seq
INCREMENT BY 10START WITH 300MAXVALUE 9999NOCACHENOCYCLE;
300 310 320 330 340 350 360 .....99999 ask for NEXTVAL = 300 – it becomes CURRVAL the number
just generated
in HTMLDB once you return the NEXTVAL from the sequence you no longer have the “session” and the database no longer knows what’s the CURVAL
Marge Hohly 24
Using a Sequence to INSERT INSERT INTO employees VALUES
(emp_emp_id_seq.NEXTVAL, ‘Kramer’, ‘Wilson’, ‘KWILSON’, ‘803.245.4642’, ’11-FEB-87’, ‘AD_ASST’, 5000, NULL, 101, 10);
Marge Hohly 25
NEXTVAL and CURRVAL NEXTVAL is a pseudocolumn used to return the
next available sequence value CURRVAL is a pseudocolumn used to obtain the
last-used sequence value NEXTVAL must be issued before CURRVAL
contains a value NEXTVAL and CURRVAL must be qualified with
a sequence name: emp_emp_id_seq.nextval
Marge Hohly 26
Modifying & Deleting a Sequence
ALTER SEQUENCE emp_emp_id_seqINCREMENT BY 5MAXVALUE 9999NOCACHENOCYCLE:
DROP SEQUENCE emp_emp_id_seq;
Marge Hohly 27
Sequence Gaps Gaps (nonsequential numbers) can
be generated by: rolling back a statement containing a
sequence, the number is lost a system crash. If the sequence caches
values into the memory and the system crashes, these values are lost.
the same sequence being used for multiple tables. If you do so, each table can contain gaps in the sequential numbers
Marge Hohly 28
What is an Index? A schema object that can speed up the retrieval of rows
by using a POINTER (isles in a grocery store) If you do not have an index on the column you’re
selecting, then a full table scan occurs Unique Index – Automatically created when you define
a column in a table to have a PRIMARY KEY or a UNIQUE KEY constraint.
Non-Unique Index – An index that a user can create to speed up access to the rows For example, to optimize joins, you can create an index
on the FOREIGN KEY column, which speeds up the search to match rows to the PRIMARY KEY column.
Marge Hohly 29
Example of an INDEX WHEN TO CREATE AN INDEX
The column contains a wide range of values A column contains a large number of null values One or more columns are frequently used together in a
WHERE clause or a join condition The table is large and most queries are expected to retrieve
less than 2-4% of the rows. WHEN NOT TO CREATE AN INDEX
The table is small The columns are not often used as a condition in the query Most queries are expected to retrieve more than 2-4% of the
rows in the table The table is updated frequently – DML required index updates The indexed columns are referenced as part of an expression
Marge Hohly 30
Example of an INDEX CREATE INDEX d_cds_name_email_idx
ON d_clients(last_name, email);
DROP INDEX d_cds_name_email_idx;
Marge Hohly 31
Example of a SYNONYM CREATE [PUBLIC] SYNONYM
synonym_nameFOR object;
CREATE SYNONYM empFOR ussc_bhs_sql01_s02.employees; PUBLIC: creates a synonym accessible to all users (we
don’t have the privilege to use PUBLIC in HTML_DB) synonym_name: is the name of the synonym to be created object: identifies the object for which the synonym is
created -A private synonym name must be distinct from all other
objects owned by the same user.