Download presentation
Presentation is loading. Please wait.
Published byRoberta Harvey Modified over 9 years ago
1
Database Programming Sections 11 & 12 – Creating, and Managing Views, Sequences, Indexes, and Synonymns
2
Marge Hohly2 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
3
Marge Hohly3 Example of a View CREATE VIEW view_employees AS SELECT first_name, last_name, email FROM employees WHERE employee_id BETWEEN 100 and 124; SELECT * FROM view_employees;
4
Marge Hohly4 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
5
Marge Hohly5 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_cds AS 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, year FROM d_cds;
6
Marge Hohly6 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
7
Marge Hohly7 Simple vs. Complex FeatureSimple ViewComplex View Number of tables used to derive data OneOne or more Can contain functions NoYes Can contain groups of data NoYes Can perform DML operations through a view YesNot always
8
Marge Hohly8 Simple View Example CREATE VIEW view_copy_d_cds(“CD Number”, Title, “Year Recorded”) AS SELECT cd_number, title, year FROM copy_d_cds;
9
Marge Hohly9 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 e WHERE c.client_number = e.client_number;
10
Marge Hohly10 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_cds AS SELECT cd_number, producer, title, year FROM copy_d_cds;
11
Marge Hohly11 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
12
Marge Hohly12 WITH CHECK OPTION CONSTRAINT CREATE OR REPLACE VIEW view_dept50 AS SELECT department_id, employee_id, first_name, last_name, salary FROM employees WHERE department_id = 50 WITH CHECK OPTION CONSTRAINT view_dept50_check; UPDATE view_dept50 SET department_id = 190 WHERE employee_id = 141; NOTE: ORA-01402: view WITH CHECK OPTION where-clause violation
13
Marge Hohly13 WITH READ ONLY CONSTRAINT CREATE OR REPLACE VIEW view_dept50 AS SELECT department_id, employee_id, first_name, last_name, salary FROM employees WHERE department_id = 50 WITH READ ONLY CONSTRAINT view_dept50_read; DELETE FROM view_dept50 WHERE employee_id = 144; ORA-01752: cannot delete from view without exactly one key-preserved table
14
Marge Hohly14 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;
15
Marge Hohly15 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
16
Marge Hohly16 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.
17
Marge Hohly17 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
18
Marge Hohly18 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.
19
Marge Hohly19 Inline View Example SELECT e.name, e.description, p.maxrange, p.code FROM d_events e, (SELECT code, max(high_range) maxrange FROM d_packages GROUP BY code) p WHERE e.package_code = p.code AND 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.
20
Marge Hohly20 Inline View Example SELECT code, max(high_range) maxrange FROM d_packages GROUP BY code;
21
Marge Hohly21 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, cost FROM (SELECT name, cost FROM d_events ORDER BY cost DESC) WHERE ROWNUM <= 2;
22
Marge Hohly22 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
23
Marge Hohly23 Example of a Sequence CREATE SEQUENCE emp_emp_id_seq INCREMENT BY 10 START WITH 300 MAXVALUE 9999 NOCACHE NOCYCLE; 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
24
Marge Hohly24 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);
25
Marge Hohly25 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
26
Marge Hohly26 Modifying & Deleting a Sequence ALTER SEQUENCE emp_emp_id_seq INCREMENT BY 5 MAXVALUE 9999 NOCACHE NOCYCLE: DROP SEQUENCE emp_emp_id_seq;
27
Marge Hohly27 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
28
Marge Hohly28 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.
29
Marge Hohly29 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
30
Marge Hohly30 Example of an INDEX CREATE INDEX d_cds_name_email_idx ON d_clients(last_name, email); DROP INDEX d_cds_name_email_idx;
31
Marge Hohly31 Example of a SYNONYM CREATE [PUBLIC] SYNONYM synonym_name FOR object; CREATE SYNONYM emp FOR 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.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.