Sams Teach Yourself SQL in 24 Hours

Sams Teach Yourself SQL in 24 Hours

By Ron Plew and Ryan Stephens

Creating Views

Views are created using the CREATE VIEW statement. Views can be created from a single table, multiple tables, or another view. To create a view, a user must have the appropriate system privilege according to the specific implementation.

The basic CREATE VIEW syntax is as follows:

   syntax_icon.gif
CREATE [RECURSIVE]VIEW VIEW_NAME
[COLUMN NAME [,COLUMN NAME]]
[OF UDT NAME [UNDER TABLE NAME]
[REF IS COLUMN NAME SYSTEM GENERATED |USER GENERATED | DERIVED]
[COLUMN NAME WITH OPTIONS SCOPE TABLE NAME]]
 AS
{SELECT STATEMENT}
[WITH [CASCADED | LOCAL] CHECK OPTION]

The following subsections explore different methods for creating views using the CREATE VIEW statement.

Creating a View from a Single Table

A view can be created from a single table. The WITH CHECK OPTION is discussed later this hour.

The syntax is as follows:

   syntax_icon.gif
CREATE VIEW VIEW_NAME AS
SELECT * | COLUMN1 [, COLUMN2 ]
FROM TABLE_NAME
[ WHERE EXPRESSION1 [, EXPRESSION2 ]]
[ WITH CHECK OPTION ]
[ GROUP BY ]

The simplest form for creating a view is one based on the entire contents of a single table, as in the following example:

   mysql_icon.gif
   input_icon.gif

   CREATE VIEW CUSTOMERS AS

   SELECT *

   FROM CUSTOMER_TBL;

   output_icon.gif
View created.

The next example narrows the contents for a view by selecting only specified columns from the base table:

   mysql_icon.gif
   input_icon.gif

   CREATE VIEW EMP_VIEW AS

   SELECT LAST_NAME, FIRST_NAME, MIDDLE_NAME

   FROM EMPLOYEE_TBL;

   output_icon.gif
View Created.

The following is an example of how columns from the BASE TABLE can be combined or manipulated to form a column in a view. The view column is titled NAME by using an alias in the SELECT clause.

   mysql_icon.gif
   input_icon.gif

   CREATE VIEW NAMES AS

   SELECT LAST_NAME || ', ' ||FIRST_NAME || ' ' || MIDDLE_NAME NAME

   FROM EMPLOYEE_TBL;

   output_icon.gif
View created.

Now you select all data from the view that you created, called NAMES.

   input_icon.gif

   SELECT *

   FROM NAMES;

   NAME

   output_icon.gif
-----------------
STEPHENS, TINA D
PLEW, LINDA C
GLASS, BRANDON S
GLASS, JACOB
WALLACE, MARIAH
SPURGEON, TIFFANY

6 rows selected.

The following example shows how to create a view with summarized data from one or more underlying tables:

   mysql_icon.gif
   input_icon.gif

   CREATE VIEW CITY_PAY AS

   SELECT E.CITY, AVG(P PAY_RATE) AVG_PAY

   FROM EMPLOYEE_TBL E,
     
   EMPLOTEE_PAY_TBL P

   WHERE E.EMP_ID = P.EMP_ID

   GROUP BY E.CITY;

   output_icon.gif
View created.

Now, if you select from your summarized view:

   input_icon.gif

   SELECT *

   FROM CITY_PAY;

   output_icon.gif
CITY            AVG_PAY
--------------- -------
GREENWOOD
INDIANAPOLIS   13.33333
WHITELAND

3 rows selected.

By summarizing a view, SELECT statements that may occur in the future are simplified against the underlying table of the view.

Creating a View from Multiple Tables

A view can be created from multiple tables by using a JOIN in the SELECT statement. WITH CHECK OPTION is discussed later this hour. The syntax is as follows:

   syntax_icon.gif
CREATE VIEW VIEW_NAME AS
SELECT * | COLUMN1 [, COLUMN2 ]
FROM TABLE_NAME1, 
   TABLE_NAME2 [, TABLE_NAME3 ]
WHERE TABLE_NAME1 = TABLE_NAME2
[ AND TABLE_NAME1 = TABLE_NAME 3 ]
[ EXPRESSION1 ][, EXPRESSION2 ]
[ WITH CHECK OPTION ]
[ GROUP BY ]

The following is an example of creating a view from multiple tables:

   mysql_icon.gif
   input_icon.gif

   CREATE VIEW EMPLOYEE_SUMMARY AS

   SELECT E.EMP_ID, E.LAST_NAME, P.POSITION, P.DATE_HIRE, P.PAY_RATE

   FROM EMPLOYEE_TBL E,
     
   EMPLOYEE PAY_TBL P

   WHERE E.EMP_ID = P.EMP_ID;

   output_icon.gif
View created.

Remember that when selecting data from multiple tables, the tables must be joined by common columns in the WHERE clause. A view is nothing more than a SELECT statement itself; therefore, tables are joined in a view definition the same as they are in a regular SELECT statement. Recall the use of table aliases to simplify the readability of a multiple-table query.

Creating a View from a View

A view can be created from another view using the following format:

   syntax_icon.gif
CREATE VIEW2 AS
SELECT * FROM VIEW1

Do Not Create Views too Deep

A view can be created from a view many layers deep (a view of a view of a view, and so on). How deep you can go is implementation-specific. The only problem with creating views based on other views is their manageability. For example, suppose that you create VIEW2 based on VIEW1 and then create VIEW3 based on VIEW2. If VIEW1 is dropped, VIEW2 and VIEW3 are no good. The underlying information that supports these views no longer exists. Therefore, always maintain a good understanding of the views in the database and on which other objects those views rely. See Figure 20.2 on view dependency.

20fig02.gif

Figure 20.2 View dependencies.

Figure 20.2 shows the relationship of views that are dependent not only on tables, but on other views. VIEW1 and VIEW2 are dependent on the TABLE. VIEW3 is dependent on VIEW1. VIEW4 is dependent on both VIEW1 and VIEW2. VIEW5 is dependent on VIEW2. Based on these relationships, the following can be concluded:

WITH CHECK OPTION

WITH CHECK OPTION is a CREATE VIEW statement option. The purpose of WITH CHECK OPTION is to ensure that all UPDATEs and INSERTs satisfy the condition(s) in the view definition. If they do not satisfy the condition(s), the UPDATE or INSERT returns an error. WITH CHECK OPTION has two options of its own: CASCADED and LOCAL. WITH CHECK OPTION actually enforces referential integrity by checking the view's definition to see that it is not violated.

The following is an example of creating a view with WITH CHECK OPTION:

   mysql_icon.gif
   input_icon.gif

   CREATE VIEW EMPLOYEE_PAGERS AS

   SELECT LAST_NAME, FIRST_NAME, PAGER

   FROM EMPLOYEE_TBL

   WHERE PAGER IS NOT NULL

   WITH CHECK OPTION;

   output_icon.gif
View created.

WITH CHECK OPTION in this case should deny the entry of any NULL values in the view's PAGER column because the view is defined by data that does not have a NULL value in the PAGER column.

Try to insert a NULL value in the PAGER column:

   input_icon.gif

   INSERT INTO EMPLOYEE PAGERS

   VALUES ('SMITH','JOHN',NULL);

   output_icon.gif
insert into employee_pagers
            *
ERROR at line 1:
ORA-01400: mandatory (NOT NULL) column is missing or NULL during insert

WITH CHECK OPTION worked.

CASCADED Versus LOCAL

There are two options when choosing to use WITH CHECK OPTION during creation of a view from a view: CASCADED and LOCAL. CASCADED is the default, assumed if neither is specified. The CASCADED option checks all underlying views, all integrity constraints during an update for the BASE TABLE, and against defining conditions in the second view. The LOCAL option is used to check only integrity constraints against both views and the defining conditions in the second view, not the underlying base table. Therefore, it is safer to create views with the CASCADED option because the base table's referential integrity is preserved.

Updating a View

A view can be updated under certain conditions:

Review Hour 14, "Using Subqueries to Define Unknown Data," for the UPDATE command's syntax.

Inserting Rows into a View

Rows of data can be inserted into a view. The same rules that apply to the UPDATE command also apply to the INSERT command. Review Hour 14 for the syntax of the INSERT command.

Deleting Rows from a View

Rows of data can be deleted from a view. The same rules that apply to the UPDATE and INSERT commands apply to the DELETE command. Review Hour 14 for the syntax of the DELETE command.

Joining Views with Tables and Other Views

A view can be joined with tables and with other views. The same principles apply to joining views with tables and other views that apply to joining tables to other tables. Review Hour 13, "Joining Tables in Queries," on the joining of tables.

Creating a Table from a View

A table can be created from a view, just as a table can be created from another table (or a view from another view).

The syntax is as follows:

   syntax_icon.gif
CREATE TABLE TABLE_NAME AS
SELECT {* | COLUMN1 [, COLUMN2 ]
FROM VIEW_NAME
[ WHERE CONDITION1 [, CONDITION2 ]
[ ORDER BY ]

First, create a view based on two tables:

   mysql_icon.gif
   input_icon.gif

   CREATE VIEW ACTIVE_CUSTOMERS AS

   SELECT C.*

   FROM CUSTOMER_TBL C,
     
   ORDERS_TBL O

   WHERE C.CUST_ID = O.CUST_ID;

   output_icon.gif
View created.

Next, create a table based on the previously created view:

   input_icon.gif

   CREATE TABLE CUSTOMER_ROSTER_TBL AS

   SELECT CUST_ID, CUST_NAME

   FROM ACTIVE_CUSTOMERS;

   output_icon.gif
Table created.

Finally, select data from the table, the same as any other table:

   input_icon.gif

   SELECT *

   FROM CUSTOMER_ROSTER_TBL;

   output_icon.gif
CUST_ID    CUST_NAME
---------- ------------------
232        LESLIE GLEASON
12         MARYS GIFT SHOP
43         SCHYLERS NOVELTIES
090        WENDY WOLF
287        GAVINS PLACE
432        SCOTTYS MARKET

6 rows selected.

Views and the ORDER BY Clause

The ORDER BY clause cannot be used in the CREATE VIEW statement; however, the GROUP BY clause when used in the CREATE VIEW statement has the same effect as an ORDER BY clause.

The following is an example of a GROUP BY clause in a CREATE VIEW statement:

   mysql_icon.gif
   input_icon.gif

   CREATE VIEW NAMES2 AS

   SELECT LAST_NAME || ', ' || FIRST_NAME || ' ' ||MIDDLE_NAME

   NAME

   FROM EMPLOYEE_TBL

   GROUP BY LAST_NAME || ', ' || FIRST_NAME || ' ' ||

   MIDDLE_NAME;

   output_icon.gif
View created.

If you select all data from the view, the data is in alphabetical order (because you grouped by NAME).

   input_icon.gif

   SELECT *

   FROM NAMES2;

   output_icon.gif
NAME
-----------------
GLASS, BRANDON S
GLASS, JACOB
PLEW, LINDA C
SPURGEON, TIFFANY
STEPHENS, TINA D
WALLACE, MARIAH

6 rows selected.

Share ThisShare This

Informit Network