- Sams Teach Yourself SQL in 24 Hours, Third Edition
- Table of Contents
- Copyright
- About the Authors
- Acknowledgments
- Tell Us What You Think!
- Introduction
- Part I: A SQL Concepts Overview
- Hour 1. Welcome to the World of SQL
- SQL Definition and History
- SQL Sessions
- Types of SQL Commands
- An Introduction to the Database Used in This Book
- Summary
- Q&A
- Workshop
- Part II: Building Your Database
- Hour 2. Defining Data Structures
- What Is Data?
- Basic Data Types
- Summary
- Q&A
- Workshop
- Hour 3. Managing Database Objects
- What Are Database Objects?
- What Is a Schema?
- A Table: The Primary Storage for Data
- Integrity Constraints
- Summary
- Q&A
- Workshop
- Hour 4. The Normalization Process
- Normalizing a Database
- Summary
- Q&A
- Workshop
- Hour 5. Manipulating Data
- Overview of Data Manipulation
- Populating Tables with New Data
- Updating Existing Data
- Deleting Data from Tables
- Summary
- Q&A
- Workshop
- Hour 6. Managing Database Transactions
- What Is a Transaction?
- What Is Transactional Control?
- Transactional Control and Database Performance
- Summary
- Q&A
- Workshop
- Part III: Getting Effective Results from Queries
- Hour 7. Introduction to the Database Query
- What Is a Query?
- Introduction to the <tt>SELECT</tt> Statement
- Examples of Simple Queries
- Summary
- Q&A
- Workshop
- Hour 8. Using Operators to Categorize Data
- What Is an Operator in SQL?
- Comparison Operators
- Logical Operators
- Conjunctive Operators
- Negating Conditions with the <tt>NOT</tt> Operator
- Arithmetic Operators
- Summary
- Q&A
- Workshop
- Hour 9. Summarizing Data Results from a Query
- What Are Aggregate Functions?
- Summary
- Q&A
- Workshop
- Hour 10. Sorting and Grouping Data
- Why Group Data?
- The <tt>GROUP BY</tt> Clause
- <tt>GROUP BY</tt> Versus <tt>ORDER BY</tt>
- The <tt>HAVING</tt> Clause
- Summary
- Q&A
- Workshop
- Hour 11. Restructuring the Appearance of Data
- The Concepts of ANSI Character Functions
- Various Common Character Functions
- Miscellaneous Character Functions
- Mathematical Functions
- Conversion Functions
- The Concept of Combining Character Functions
- Summary
- Q&A
- Workshop
- Hour 12. Understanding Dates and Times
- How Is a Date Stored?
- Date Functions
- Date Conversions
- Summary
- Q&A
- Workshop
- Part IV: Building Sophisticated Database Queries
- Hour 13. Joining Tables in Queries
- Selecting Data from Multiple Tables
- Types of Joins
- Join Considerations
- Summary
- Q&A
- Workshop
- Hour 14. Using Subqueries to Define Unknown Data
- What Is a Subquery?
- Embedding a Subquery Within a Subquery
- Summary
- Q&A
- Workshop
- Hour 15. Combining Multiple Queries into One
- Single Queries Versus Compound Queries
- Why Would I Ever Want to Use a Compound Query?
- Compound Query Operators
- Using an <tt>ORDER BY</tt> with a Compound Query
- Using <tt>GROUP BY</tt> with a Compound Query
- Retrieving Accurate Data
- Summary
- Workshop
- Q&A
- Part V: SQL Performance Tuning
- Hour 16. Using Indexes to Improve Performance
- What Is an Index?
- How Do Indexes Work?
- The <tt>CREATE INDEX</tt> Command
- Types of Indexes
- When Should Indexes Be Considered?
- When Should Indexes Be Avoided?
- Summary
- Q&A
- Workshop
- Hour 17. Improving Database Performance
- What Is SQL Statement Tuning?
- Database Tuning Versus SQL Tuning
- Formatting Your SQL Statement
- Full Table Scans
- Other Performance Considerations
- Performance Tools
- Summary
- Q&A
- Workshop
- Part VI: Using SQL to Manage Users and Security
- Hour 18. Managing Database Users
- Users Are the Reason
- The Management Process
- Tools Utilized by Database Users
- Summary
- Q&A
- Workshop
- Hour 19. Managing Database Security
- What Is Database Security?
- How Does Security Differ from User Management?
- What Are Privileges?
- Controlling User Access
- Controlling Privileges Through Roles
- Summary
- Q&A
- Workshop
- Part VII: Summarized Data Structures
- Hour 20. Creating and Using Views and Synonyms
- What Is a View?
- Creating Views
- Dropping a View
- What Is a Synonym?
- Summary
- Q&A
- Workshop
- Hour 21. Working with the System Catalog
- What Is the System Catalog?
- How Is the System Catalog Created?
- What Is Contained in the System Catalog?
- Examples of System Catalog Tables by Implementation
- Querying the System Catalog
- Updating System Catalog Objects
- Summary
- Q&A
- Workshop
- Part VIII: Applying SQL Fundamentals in Today's World
- Hour 22. Advanced SQL Topics
- Advanced Topics
- Cursors
- Stored Procedures and Functions
- Triggers
- Dynamic SQL
- Call-Level Interface
- Using SQL to Generate SQL
- Direct Versus Embedded SQL
- Summary
- Q&A
- Workshop
- Hour 23. Extending SQL to the Enterprise, the Internet, and the Intranet
- SQL and the Enterprise
- Accessing a Remote Database
- Accessing a Remote Database Through a Web Interface
- SQL and the Internet
- SQL and the Intranet
- Summary
- Q&A
- Workshop
- Hour 24. Extensions to Standard SQL
- Various Implementations
- Examples of Extensions from Some Implementations
- Interactive SQL Statements
- Summary
- Q&A
- Workshop
- Part IX: Appendixes
- Appendix A. Common SQL Commands
- SQL Statements
- SQL Clauses
- Appendix B. Using MySQL for Exercises
- Windows Installation Instructions
- Linux Installation Instructions
- Appendix C. Answers to Quizzes and Exercises
- Hour 1, "Welcome to the World of SQL"
- Hour 2, "Defining Data Structures"
- Hour 3, "Managing Database Objects"
- Hour 4, "The Normalization Process"
- Hour 5, "Manipulating Data"
- Hour 6, "Managing Database Transactions"
- Hour 7, "Introduction to the Database Query"
- Hour 8, "Using Operators to Categorize Data"
- Hour 9, "Summarizing Data Results from a Query"
- Hour 10, "Sorting and Grouping Data"
- Hour 11, "Restructuring the Appearance of Data"
- Hour 12, "Understanding Dates and Time"
- Hour 13, "Joining Tables in Queries"
- Hour 14, "Using Subqueries to Define Unknown Data"
- Hour 15, "Combining Multiple Queries into One"
- Hour 16, "Using Indexes to Improve Performance"
- Hour 17, "Improving Database Performance"
- Hour 18, "Managing Database Users"
- Hour 19, "Managing Database Security"
- Hour 20, "Creating and Using Views and Synonyms"
- Hour 21, "Working with the System Catalog"
- Hour 22, "Advanced SQL Topics"
- Hour 23, "Extending SQL to the Enterprise, the Internet, and the Intranet"
- Hour 24, "Extensions to Standard SQL"
- Appendix D. <tt>CREATE TABLE</tt> Statements for Book Examples
- <tt>EMPLOYEE_TBL</tt>
- <tt>EMPLOYEE_PAY_TBL</tt>
- <tt>CUSTOMER_TBL</tt>
- <tt>ORDERS_TBL</tt>
- <tt>PRODUCTS_TBL</tt>
- Appendix E. <tt>INSERT</tt> Statements for Data in Book Examples
- <tt>INSERT</tt> Statements
- Appendix F. Glossary
- Appendix G. Bonus Exercises
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:
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:
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:
CREATE VIEW CUSTOMERS AS SELECT * FROM CUSTOMER_TBL; View created.
The next example narrows the contents for a view by selecting only specified columns from the base table:
CREATE VIEW EMP_VIEW AS SELECT LAST_NAME, FIRST_NAME, MIDDLE_NAME FROM EMPLOYEE_TBL; 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.
CREATE VIEW NAMES AS SELECT LAST_NAME || ', ' ||FIRST_NAME || ' ' || MIDDLE_NAME NAME FROM EMPLOYEE_TBL; View created.
Now you select all data from the view that you created, called NAMES.
SELECT * FROM NAMES; NAME ----------------- 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:
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; View created.
Now, if you select from your summarized view:
SELECT * FROM CITY_PAY; 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:
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:
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; 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:
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.
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:
CREATE VIEW EMPLOYEE_PAGERS AS SELECT LAST_NAME, FIRST_NAME, PAGER FROM EMPLOYEE_TBL WHERE PAGER IS NOT NULL WITH CHECK OPTION; 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:
INSERT INTO EMPLOYEE PAGERS VALUES ('SMITH','JOHN',NULL); 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:
CREATE TABLE TABLE_NAME AS SELECT {* | COLUMN1 [, COLUMN2 ] FROM VIEW_NAME [ WHERE CONDITION1 [, CONDITION2 ] [ ORDER BY ]
First, create a view based on two tables:
CREATE VIEW ACTIVE_CUSTOMERS AS SELECT C.* FROM CUSTOMER_TBL C, ORDERS_TBL O WHERE C.CUST_ID = O.CUST_ID; View created.
Next, create a table based on the previously created view:
CREATE TABLE CUSTOMER_ROSTER_TBL AS SELECT CUST_ID, CUST_NAME FROM ACTIVE_CUSTOMERS; Table created.
Finally, select data from the table, the same as any other table:
SELECT * FROM CUSTOMER_ROSTER_TBL; 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:
CREATE VIEW NAMES2 AS SELECT LAST_NAME || ', ' || FIRST_NAME || ' ' ||MIDDLE_NAME NAME FROM EMPLOYEE_TBL GROUP BY LAST_NAME || ', ' || FIRST_NAME || ' ' || MIDDLE_NAME; View created.
If you select all data from the view, the data is in alphabetical order (because you grouped by NAME).
SELECT * FROM NAMES2; NAME ----------------- GLASS, BRANDON S GLASS, JACOB PLEW, LINDA C SPURGEON, TIFFANY STEPHENS, TINA D WALLACE, MARIAH 6 rows selected.