Presentation is loading. Please wait.

Presentation is loading. Please wait.

Database Programming Sections 11 – Creating, and Managing Views, Sequences, Indexes, and Synonymns.

Similar presentations


Presentation on theme: "Database Programming Sections 11 – Creating, and Managing Views, Sequences, Indexes, and Synonymns."— Presentation transcript:

1 Database Programming Sections 11 – Creating, and Managing Views, Sequences, Indexes, and Synonymns

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 Your role as a DBA -Business view – all access to only required data with assigned permissions -Questions: should the employees have full access? Is it wise to have all able to input data -View is a virtual representation of a table (a virtual table) -View has NO data but rather a way/path to examine data in a base table -View sees data in the base tables, like a window provides a view -NOT REAL DATA Marge Hohly

3 Example of a View CREATE VIEW view_employees AS SELECT first_name, last_name, FROM employees WHERE employee_id BETWEEN 100 and 124; SELECT * FROM view_employees; -view_employees is the name of the view -View has NO DATA, it is a virtual table -The SELECT statement is a subquery creating a virtual 3 column table -The above view is selective access to data -It decreases the complexity executing queries -SELECT * FROM view-employees; We’ll start out by examining views. The idea of a view is that it is a virtual representation of underlying table data. Let’s use an analogy of a window. If you think of the tables on which a view is based, these are called the base tables. With a simple view we can look at only part of the tables, just like you can look into a window in a house and see only part of what is inside of the house. In this case, our window is defined so that the user can look at only certain parts of the table according to the desires of the database administrator or the table owner. A view is defined as a table of logical subsets or combinations of data based on a table or another view. The view itself does not have data, but it provides a way to examine the data in the underlying table. It presents data from one or more tables in one place. Let’s look at the example in the slide. CREATE VIEW are the keywords we start with, then we name the view, in this case view underscore employees. The word AS describes what the view will look like. Then we use a subquery: SELECT first_name, last_name, FROM employees WHERE employee_id BETWEEN 100 AND 124. Notice that unlike a normal subquery, there are no parentheses around the SELECT statement. In this case the view contains only three columns and a subset of the original table data as indicated by the WHERE clause in the subquery. Marge Hohly

4 Why use view? Views restrict access to base table data because the view can display selective columns from the table Views can be used to reduce the complexity of executing queries based on more complicated SELECT statements. For example, the creator of the view can construct join statements that retrieve data from multiple tables. The user of the view neither sees the underlying code nore have to create it. The user, through the view, interacts with the database using simple queries. One use of a view is to restrict access to data because the view can display selective columns from the table. Additionally, views can be used to reduce the complexity of executing queries based on more complicated SELECT statements. For example, the creator of the view can construct join statements that retrieve data from multiple tables. The user of the view does not see the underlying code or how to create it. The user, through the view, interacts with the database using simple queries. Views can be used to retrieve data from several tables providing data independence for users. Users can view the same data, in different ways. Views also provide groups of users with access to data according to their particular permissions or criteria. Marge Hohly

5 Why use Views? Cont. Views can be used to retrieve data from several tables, providing data independence for users. Users can view the same data in different ways. Views provide groups of users with access to data according to their particular permissions of criteria. 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 CREATE OR REPLACE VIEW view_of_animals AS SELECT field1, field2, field3 FROM anmals WITH READ ONLY; FORCE – create view with or without a base table NOFORCE – is default Alias define column aliases within the view Check option constraint – if named only applies to the rows accessible to the view that it can add or delete READ ONLY constraint – NO DML operations can be done on the view, can only look at the information thru the view but can’t change it Here we see the syntax for creating a view. All the information in brackets is optional. Let’s look at the syntax in detail. The first word is CREATE. OR REPLACE is optional, then FORCE or NOFORCE. NOFORCE is the default option; it is not needed. If FORCE is used, what this does is it creates a view regardless of whether or not the base tables exist. The next word in our syntax is VIEW, then we name the view, in this case view underscore name and additional names or aliases for the view may also be specified. The next word is AS, followed by the subquery, the SELECT statement that creates the data being placed into the view. Next is an optional WITH CHECK OPTION. CHECK OPTION is a constraint; if the constraint is named, it comes after the CHECK OPTION following the word CONSTRAINT and then constraint name. WITH READ ONLY is another option. It is also a constraint. The WITH CHECK OPTION constraint specifies that only rows accessible to the view can be inserted and deleted. We’ll see an example later. WITH READ ONLY means that no DML operations can be formed on this view. Users can only look at the information but they cannot change any information through the view. There are two types of views, simple views and complex views. We’ll look at these shortly. Marge Hohly

7 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 -ORDER BY effects data output to the screen and a view is a path thus can not be used in a VIEW -A view is not output to screen but a definition of what is available thru the view. The following are some 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 because ORDER BY is only used to sort output to the screen and a view is not output. It is a definition of what data will be in the view. Once a view is created, you cannot change it with the ALTER VIEW command; instead, use the CREATE OR REPLACE to replace the original view with a new version without having to drop it or re-grant object privileges previously granted. This will make more sense to you when we talk about privileges later. A view can also contain new column names, aliases for the original column names brought back from the subquery. Marge Hohly

8 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; Marge Hohly

9 Simple vs. Complex Feature Simple View Complex View One One or more No
Number of tables used to derive data One One or more Can contain functions No Yes Can contain groups of data Can perform DML operations (insert, update, Delete) through a view Not always DML operations can be always done on simple view ONLY if they do not have a READ ONLY constraint. There are two types of views: simple and complex. This slide shows the difference between the two types of views. A simple view can only be derived from one table. It cannot contain functions. It cannot contain groupings of data. And, it can allow DML operations as long as the WITH READ ONLY option is not part of the syntax for creating the view. A complex view can be from one or more tables. It can contain functions. It can contain groups of data. And it can sometimes have DML operations performed against it. Marge Hohly

10 Simple View CREATE VIEW view1_copy_d_cds AS SELECT cd_number, title, producer, year FROM d_cds; Data from one table only and does not contain a join function or group function INSERT, UPDATE, DELETE, & MERGE operations affecting the base table are possible Marge Hohly

11 Simple View Example CREATE VIEW view2_copy_d_cds AS SELECT cd_number “Number”, title AS “Title”, year AS “Year Recorded”) FROM copy_d_cds; CREATE VIEW view3_copy_d_cds(Number, Title, Year_Recorded) AS SELECT cd_number, title, year FROM d_cds; This slide demonstrates two examples of the CREATE VIEW syntax using aliases for the new column names and only one table. Notice the syntax. CREATE VIEW comes first, then the name of the view. The first example creates aliases for the columns in the view in the SELECT statement. In the second example, the column aliases for the view are included. Finally, the AS SELECT statement is included and specifies the original column names from the table. On your own, create the view using either example in Oracle Application Express. You should already have a copy of the d underscore cds table in your schema. Confirm the creation of the view by executing SELECT star FROM view_copy_d_cds. CREATE TABLE copy_d_cds AS (SELECT * FROM d_cds); -without aliases CREATE VIEW view_copy_d_cds AS SELECT cd_number,title,year FROM copy_d_cds; -From single table -No join function or group functions -Because simple could perform INSERT, UPDATE, DELETE, & MERGE thru view Marge Hohly

12 Simple View Can create a view whether or not a base table exists
User word FORCE in CREATE VIEW statement NOFORCE is the default -a DBA during development when waiting for permissions to be granted to reference(base) object -The view is invalid Marge Hohly

13 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; Reasons complex: 1 or more tables Group functions Functions like TO_CHAR Normally a view retains the same data types as the base table. In this example- the view would have a character data type where the base table data type would be a date data type. Thus can’t use any DML functions but only perform queries This slide shows the creation of a complex view. The view is complex for two reasons. The first is that the information comes from two different tables, in this case the d underscore clients table and the d underscore events table. A join condition allows these tables to be used in the same view. The other reason this is a complex view is because it contains a group function, in this case the TO_CHAR function. It changes the event date from a date to a character value. Normally viewed columns maintain the data type of the referring table. But, in this case, the TO_CHAR function forces a change in the data type from the base table. For this reason you cannot perform any DML functions on the view created here, only queries. Marge Hohly

14 Complex View Group functions can be added to complex-view statements
CREATE VIEW view_dj_cds(Title, Song, Min_Year, Max_year) AS SELECT c.title, t.song_id, MIN(c.year), MAX(c.year) FROM d_cds c, d_track_listings t WHERE c.cd_number = t.cd_number GROUP BY c.cd_number, c.title, t.song_id; Note: group functions MIN and MAX Thus, NO DML commands allowed Marge Hohly

15 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; Run command. You can’t really modify a view. What you have to do is recreate the view by using the syntax, CREATE OR REPLACE VIEW. That will eliminate the old view and replace it with the new information. In the example on the slide, we are adding the producer column to the view underscore copy underscore d underscore cds view. - Can’t modify a view rather create or replace which deletes the old view and replaces it with a new view. This command added a producer column to view and the data into that column. Marge Hohly

16 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 Chapter 11 lesson 2 VIEW does not contain real data it is a way to access the underlying base tables 2 options to control data changes With a CHECK OPTION constraint – This allows only changes within the domain of the view With READ ONLY – this allows no changes to the data in the underlying base table. Normally Data Manipulation Language operations such as, INSERT, UPDATE, and DELETE, can be formed on simple views. What really happens is the data in the underlying base tables is changed. Remember, the view does not actually contain data; it is a way of viewing the original table data. If the view owner or the database administrator wishes to restrict people from changing the data in a view, there are two possible options. The first is to specify WITH CHECK OPTION in the create view statement. This ensures that Database Manipulation Language operations performed on the view stay within the domain of the view. We’ll see an example on the next slide. The second option is to specify WITH READ ONLY in the create view statement to ensure that no DML operations can occur through the view. Marge Hohly

17 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 SELECT * FROM view_dept50; Manager to see information on employees in department 50 only -update view_dept50 command above. Run the update and you will see the error because the view is for only department 50. with the CHECK OPTION constraint ou can’t move the employee from department 50 out of the domain and into department 190. This would move the record out of the domain Remember in APEX all DDL statements are auto committed SELECT * from view_dept50; This slide demonstrates creating a view including the WITH CHECK OPTION. The syntax is as follows: CREATE OR REPLACE VIEW, viewname, AS, SELECT, column names, FROM the base table. The WHERE clause restricts the data to return. WITH CHECK OPTION comes next, followed by the optional word CONSTRAINT and constraint name, in this case, view underscore dept50 underscore check. Create this view in Application Express, then execute a SELECT star to examine its contents. Now, let’s see what happens if we violate this CHECK OPTION CONSTRAINT. Try to update the view by typing the following in Application Express: UPDATE view underscore dept50 SET department underscore id equal WHERE employee underscore id equals Run this command and you will get an error. The reason for this error is because we’re only viewing employees in department 50. Changing the department number would remove this employee from the view. This is not allowed because of the WITH CHECK OPTION CONSTRAINT. Marge Hohly

18 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 -Won’t allow INSERT, UPDATE, OR DELETE commands, will get a server error -without the “OR REPLACE” command would fail because view_dept50 already exists -run command to delete the view_dept50 view -Note: error you generate due to constraint This example demonstrates the WITH READ ONLY CONSTRAINT. It starts with CREATE OR REPLACE VIEW. If you did not include the OR REPLACE part of this statement, this command would fail because a view called view underscore dept50 already exists. The OR REPLACE allows the old view to be discarded and this new view to be put in its place. Take a moment to execute this statement in Application Express. Now, try to perform a DML operation using this view, such as: DELETE FROM view underscore dept50 WHERE employee underscore id equals Try it, and see what error is generated. Marge Hohly

19 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 The DISTINCT 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; One of the 3 restrictions on views: ROWNUM is a column generated in memory of the program/command but is not part of the actual table used in the background of the result set. ROWNUM can be used as a column in the SELECT statement but it does not have existence in the base table DML restrictions: simple views dML can be performed thru the view but in COMPLEX views, DML operations are not always allowed SELECT rownum, first_name FROM employees WHERE employee_id BETWEEN 100 AND 105; There are other DML restrictions on views. This first one says that you cannot remove a row from an underlying base table if the view contains group functions, a GROUP BY clause, or the pseudocolumn ROWNUM keyword. A pseudocolumn is a column that’s generated within the memory of the program, but is not part of an actual table. It is used in the background of the results set. The pseudocolumn can be used as a column in a SELECT statement, but it does not have any existence in the database table itself. We’ll learn more about ROWNUM later. Marge Hohly

20 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 Columns defined by expressions include things like TO_CHAR Salary * 1.02 Another restriction is that you cannot modify or change data through a view if the view contains group functions, a GROUP BY clause, the pseudocolumn ROWNUM keyword, the DISTINCT keyword, or columns defined by expressions; such as, the TO CHAR column that we defined in the beginning of this section. Other examples of expressions would be a column that contained salary times 12, instead of just the column salary. Marge Hohly

21 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. -NOT NULL columns User of the view would not have access to the base table and thus not know which columns must have a value (NOT NULL) The added new row must include data for all of the NOT NULL columns in the base table. The view may not include all fo the required columns (NOT NULL) If the column is NOT NULL is not visible/available within the view it could not have data added to it and would now have null values in that column, Which is not allowed. This slide shows limitations on adding data through a view. You cannot add data through a view, if the view includes group functions, if it includes a GROUP BY clause, if it includes the pseudocolumn ROWNUM keyword, if it includes the DISTINCT keyword, if it includes columns defined by expressions, or if it does not include NOT NULL columns in the base tables. With the exception of this last bullet, all of these are characteristics of views that do not include the actual underlying base table data. The last statement about the NOT NULL requires a little additional explanation. Remember, the user of a view will not see all the columns in the table and would not know which columns in the base tables must have a value. Adding new rows must include data for all the NOT NULL columns in that row. If the row is not visible in the view, there is no way to add data for it. Marge Hohly

22 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 Chapter 11 Lesson 3 Views created for specific purposes should be deleted when no longer needed. NOTE: only the creator or the user with DROP ANY VIEW privilege can remove a view. The creator always has all privileges to the objects they create. DROP VIEW view_dept50; Dropping a view is very simple. The words DROP VIEW and then the name of the view are all that’s necessary. Again, because the view does not contain actual data, dropping a view does not affect data in any of the tables. Only the creator of the view, the database administrator, or a user with DROP ANY VIEW privileges, can remove a view. We’ll talk more about privileges later. Practice this in Application Express by dropping the view, view underscore dept50, that you created earlier. Marge Hohly

23 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. Create a temporary view in the FROM clause of the SELECT statement It is not a permanent view but exists only for the moment of the command execution Temporary view which needs to be created every time it is needed An inline view is a view without any permanence. It is a view created by the FROM clause of a SELECT statement. The view is created “on the fly” instead of saving it as a separate database object. The next example demonstrates an inline view. Marge Hohly

24 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. Example of an inline view. These tables do not exist in your database thus you can only examine the statement not run it. The inline view is a subquery in the FROM clause of the statement. Notice in the example you are joining an existing table with the results of a subquery (inline view) which has been given an alias and used only for the duration of the command. The results of the subqjery (inline view) is not saved as a database object but only exists for the moment. Inline views are commonly used to simply complex queries by removing join operations and condensing several queries into a single query. We start with a normal SELECT statement; however, in addition to a table, a SELECT statement in the FROM clause contains a subquery that brings back a certain part of another table. The subquery represents the inline view. Let’s first examine the result of the subquery. SELECT code max high underscore range maxrange FROM d underscore packages GROUP BY code. This is not a table you have in your database schema, so we can only examine it. The results of the inline view are joined with the d events table. Let’s go back and look at the result of this join. Notice that the subquery has the alias p at the end of it. The subquery is referenced in the WHERE clause using the alias p: WHERE e.package_code = p.code. Marge Hohly

25 Inline View Example SELECT code, max(high_range) maxrange FROM d_packages GROUP BY code; Marge Hohly

26 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; Looking for the top 2 values of the d_events table. Sorted in oldest to newest. This will product the top oldest events Subquery(inline view) sorts the data so it can have the outer statement select the top values Note: this is the only time the ORDER BY clause can be used in a subquery. This slide demonstrates the syntax for what we call Top-N-analysis, where ‘N’ represents a number and ‘Top’ represents that we’re looking for the highest number down to the Nth number. The example here finds the four oldest titles in the d_cds table. This Top-N-analysis is done when there is need for a sorted list and also a need for only the top few items from that list. ‘N’ becomes the number of items to be returned. Let’s examine the example in the slide from the inside out. Inside the subquery we have SELECT year comma title FROM d underscore c-ds ORDER BY year. This places the oldest title at the top of the returned list. By the way, this is the only time an ORDER BY clause can be used in a subquery. Once the subquery returns the list, the list has a pseudocolumn called ROWNUM. This list starts at the oldest title and numbers it one, and then continues numbering all the way down the list. When we add the WHERE ROWNUM less than or equal to four, this removes all of the titles, except for the top four. Then, we SELECT ROWNUM with the alias rank, which lists the ranking for the first four rows. Next the year of the CD, and a title of the CD are selected. The overall result is to bring back the four oldest titles from the table. Marge Hohly

27 Examples SELECT ROWNUM as RANK, year, title FROM (SELECT year, title FROM d_cds ORDER BY year) WHERE ROWNUM <=4; SELECT ROWNUM as TOP, last_name, first_name, salary FROM (SELECT last_name, first_name, salary FROM employees ORDER BY salary DESC) WHERE ROWNUM <=5; Marge Hohly


Download ppt "Database Programming Sections 11 – Creating, and Managing Views, Sequences, Indexes, and Synonymns."

Similar presentations


Ads by Google