Home > Articles > Web Development

📄 Contents

  1. Sams Teach Yourself SQL in 24 Hours, Third Edition
  2. Table of Contents
  3. Copyright
  4. About the Authors
  5. Acknowledgments
  6. Tell Us What You Think!
  7. Introduction
  8. Part I: A SQL Concepts Overview
  9. Hour 1. Welcome to the World of SQL
  10. SQL Definition and History
  11. SQL Sessions
  12. Types of SQL Commands
  13. An Introduction to the Database Used in This Book
  14. Summary
  15. Q&A
  16. Workshop
  17. Part II: Building Your Database
  18. Hour 2. Defining Data Structures
  19. What Is Data?
  20. Basic Data Types
  21. Summary
  22. Q&A
  23. Workshop
  24. Hour 3. Managing Database Objects
  25. What Are Database Objects?
  26. What Is a Schema?
  27. A Table: The Primary Storage for Data
  28. Integrity Constraints
  29. Summary
  30. Q&A
  31. Workshop
  32. Hour 4. The Normalization Process
  33. Normalizing a Database
  34. Summary
  35. Q&A
  36. Workshop
  37. Hour 5. Manipulating Data
  38. Overview of Data Manipulation
  39. Populating Tables with New Data
  40. Updating Existing Data
  41. Deleting Data from Tables
  42. Summary
  43. Q&A
  44. Workshop
  45. Hour 6. Managing Database Transactions
  46. What Is a Transaction?
  47. What Is Transactional Control?
  48. Transactional Control and Database Performance
  49. Summary
  50. Q&A
  51. Workshop
  52. Part III: Getting Effective Results from Queries
  53. Hour 7. Introduction to the Database Query
  54. What Is a Query?
  55. Introduction to the <tt>SELECT</tt> Statement
  56. Examples of Simple Queries
  57. Summary
  58. Q&amp;A
  59. Workshop
  60. Hour 8. Using Operators to Categorize Data
  61. What Is an Operator in SQL?
  62. Comparison Operators
  63. Logical Operators
  64. Conjunctive Operators
  65. Negating Conditions with the <tt>NOT</tt> Operator
  66. Arithmetic Operators
  67. Summary
  68. Q&amp;A
  69. Workshop
  70. Hour 9. Summarizing Data Results from a Query
  71. What Are Aggregate Functions?
  72. Summary
  73. Q&amp;A
  74. Workshop
  75. Hour 10. Sorting and Grouping Data
  76. Why Group Data?
  77. The <tt>GROUP BY</tt> Clause
  78. <tt>GROUP BY</tt> Versus <tt>ORDER BY</tt>
  79. The <tt>HAVING</tt> Clause
  80. Summary
  81. Q&amp;A
  82. Workshop
  83. Hour 11. Restructuring the Appearance of Data
  84. The Concepts of ANSI Character Functions
  85. Various Common Character Functions
  86. Miscellaneous Character Functions
  87. Mathematical Functions
  88. Conversion Functions
  89. The Concept of Combining Character Functions
  90. Summary
  91. Q&amp;A
  92. Workshop
  93. Hour 12. Understanding Dates and Times
  94. How Is a Date Stored?
  95. Date Functions
  96. Date Conversions
  97. Summary
  98. Q&amp;A
  99. Workshop
  100. Part IV: Building Sophisticated Database Queries
  101. Hour 13. Joining Tables in Queries
  102. Selecting Data from Multiple Tables
  103. Types of Joins
  104. Join Considerations
  105. Summary
  106. Q&amp;A
  107. Workshop
  108. Hour 14. Using Subqueries to Define Unknown Data
  109. What Is a Subquery?
  110. Embedding a Subquery Within a Subquery
  111. Summary
  112. Q&A
  113. Workshop
  114. Hour 15. Combining Multiple Queries into One
  115. Single Queries Versus Compound Queries
  116. Why Would I Ever Want to Use a Compound Query?
  117. Compound Query Operators
  118. Using an <tt>ORDER BY</tt> with a Compound Query
  119. Using <tt>GROUP BY</tt> with a Compound Query
  120. Retrieving Accurate Data
  121. Summary
  122. Workshop
  123. Q&amp;A
  124. Part V: SQL Performance Tuning
  125. Hour 16. Using Indexes to Improve Performance
  126. What Is an Index?
  127. How Do Indexes Work?
  128. The <tt>CREATE INDEX</tt> Command
  129. Types of Indexes
  130. When Should Indexes Be Considered?
  131. When Should Indexes Be Avoided?
  132. Summary
  133. Q&amp;A
  134. Workshop
  135. Hour 17. Improving Database Performance
  136. What Is SQL Statement Tuning?
  137. Database Tuning Versus SQL Tuning
  138. Formatting Your SQL Statement
  139. Full Table Scans
  140. Other Performance Considerations
  141. Performance Tools
  142. Summary
  143. Q&amp;A
  144. Workshop
  145. Part VI: Using SQL to Manage Users and Security
  146. Hour 18. Managing Database Users
  147. Users Are the Reason
  148. The Management Process
  149. Tools Utilized by Database Users
  150. Summary
  151. Q&amp;A
  152. Workshop
  153. Hour 19. Managing Database Security
  154. What Is Database Security?
  155. How Does Security Differ from User Management?
  156. What Are Privileges?
  157. Controlling User Access
  158. Controlling Privileges Through Roles
  159. Summary
  160. Q&amp;A
  161. Workshop
  162. Part VII: Summarized Data Structures
  163. Hour 20. Creating and Using Views and Synonyms
  164. What Is a View?
  165. Creating Views
  166. Dropping a View
  167. What Is a Synonym?
  168. Summary
  169. Q&amp;A
  170. Workshop
  171. Hour 21. Working with the System Catalog
  172. What Is the System Catalog?
  173. How Is the System Catalog Created?
  174. What Is Contained in the System Catalog?
  175. Examples of System Catalog Tables by Implementation
  176. Querying the System Catalog
  177. Updating System Catalog Objects
  178. Summary
  179. Q&amp;A
  180. Workshop
  181. Part VIII: Applying SQL Fundamentals in Today's World
  182. Hour 22. Advanced SQL Topics
  183. Advanced Topics
  184. Cursors
  185. Stored Procedures and Functions
  186. Triggers
  187. Dynamic SQL
  188. Call-Level Interface
  189. Using SQL to Generate SQL
  190. Direct Versus Embedded SQL
  191. Summary
  192. Q&amp;A
  193. Workshop
  194. Hour 23. Extending SQL to the Enterprise, the Internet, and the Intranet
  195. SQL and the Enterprise
  196. Accessing a Remote Database
  197. Accessing a Remote Database Through a Web Interface
  198. SQL and the Internet
  199. SQL and the Intranet
  200. Summary
  201. Q&amp;A
  202. Workshop
  203. Hour 24. Extensions to Standard SQL
  204. Various Implementations
  205. Examples of Extensions from Some Implementations
  206. Interactive SQL Statements
  207. Summary
  208. Q&amp;A
  209. Workshop
  210. Part IX: Appendixes
  211. Appendix A. Common SQL Commands
  212. SQL Statements
  213. SQL Clauses
  214. Appendix B. Using MySQL for Exercises
  215. Windows Installation Instructions
  216. Linux Installation Instructions
  217. Appendix C. Answers to Quizzes and Exercises
  218. Hour 1, "Welcome to the World of SQL"
  219. Hour 2, "Defining Data Structures"
  220. Hour 3, "Managing Database Objects"
  221. Hour 4, "The Normalization Process"
  222. Hour 5, "Manipulating Data"
  223. Hour 6, "Managing Database Transactions"
  224. Hour 7, "Introduction to the Database Query"
  225. Hour 8, "Using Operators to Categorize Data"
  226. Hour 9, "Summarizing Data Results from a Query"
  227. Hour 10, "Sorting and Grouping Data"
  228. Hour 11, "Restructuring the Appearance of Data"
  229. Hour 12, "Understanding Dates and Time"
  230. Hour 13, "Joining Tables in Queries"
  231. Hour 14, "Using Subqueries to Define Unknown Data"
  232. Hour 15, "Combining Multiple Queries into One"
  233. Hour 16, "Using Indexes to Improve Performance"
  234. Hour 17, "Improving Database Performance"
  235. Hour 18, "Managing Database Users"
  236. Hour 19, "Managing Database Security"
  237. Hour 20, "Creating and Using Views and Synonyms"
  238. Hour 21, "Working with the System Catalog"
  239. Hour 22, "Advanced SQL Topics"
  240. Hour 23, "Extending SQL to the Enterprise, the Internet, and the Intranet"
  241. Hour 24, "Extensions to Standard SQL"
  242. Appendix D. <tt>CREATE TABLE</tt> Statements for Book Examples
  243. <tt>EMPLOYEE_TBL</tt>
  244. <tt>EMPLOYEE_PAY_TBL</tt>
  245. <tt>CUSTOMER_TBL</tt>
  246. <tt>ORDERS_TBL</tt>
  247. <tt>PRODUCTS_TBL</tt>
  248. Appendix E. <tt>INSERT</tt> Statements for Data in Book Examples
  249. <tt>INSERT</tt> Statements
  250. Appendix F. Glossary
  251. Appendix G. Bonus Exercises
Recommended Book

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:

  • If VIEW1 is dropped, VIEW3 and VIEW4 are invalid.
  • If VIEW2 is dropped, VIEW4 and VIEW5 are invalid.
  • If the TABLE is dropped, none of the views are valid.

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:

  • The view must not involve joins.
  • The view must not contain a GROUP BY clause.
  • The view cannot contain any reference to the pseudocolumn ROWNUM.
  • The view cannot contain any group functions.
  • The DISTINCT clause cannot be used.
  • The WHERE clause cannot include a nested table expression that includes a reference to the same table as referenced in the FROM clause.

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.