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

Integrity Constraints

Integrity constraints are used to ensure accuracy and consistency of data in a relational database. Data integrity is handled in a relational database through the concept of referential integrity. There are many types of integrity constraints that play a role in referential integrity (RI).

Primary Key Constraints

newterm_icon.gif

Primary key is the term used to identify one or more columns in a table that make a row of data unique. Although the primary key typically consists of one column in a table, more than one column can comprise the primary key. For example, either the employee's Social Security number or an assigned employee identification number is the logical primary key for an employee table. The objective is for every record to have a unique primary key or value for the employee's identification number. Because there is probably no need to have more than one record for each employee in an employee table, the employee identification number makes a logical primary key. The primary key is assigned at table creation.

The following example identifies the EMP_ID column as the PRIMARY KEY for the EMPLOYEES table:

CREATE TABLE EMPLOYEE_TBL 
(EMP_ID        CHAR(9)        NOT NULL PRIMARY KEY,
EMP_NAME       VARCHAR (40)   NOT NULL,
EMP_ST_ADDR    VARCHAR (20)   NOT NULL,
EMP_CITY       VARCHAR (15)   NOT NULL,
EMP_ST         CHAR(2)        NOT NULL,
EMP_ZIP        INTEGER(5)      NOT NULL,
EMP_PHONE      INTEGER(10)     NULL,
EMP_PAGER      INTEGER(10)     NULL);

This method of defining a primary key is accomplished during table creation. The primary key in this case is an implied constraint. You can also specify a primary key explicitly as a constraint when setting up a table, as follows:

   mysql_icon.gif
CREATE TABLE EMPLOYEE_TBL
(EMP_ID        CHAR(9)        NOT NULL,
EMP_NAME       VARCHAR (40)   NOT NULL,
EMP_ST_ADDR    VARCHAR (20)   NOT NULL,
EMP_CITY       VARCHAR (15)   NOT NULL,
EMP_ST         CHAR(2)        NOT NULL,
EMP_ZIP        INTEGER(5)      NOT NULL,
EMP_PHONE      INTEGER(10)     NULL,
EMP_PAGER      INTEGER(10)     NULL,
PRIMARY KEY (EMP_ID));

The primary key constraint in this example is defined after the column comma list in the CREATE TABLE statement.

A primary key that consists of more than one column can be defined by either of the following methods:

   mysql_icon.gif
CREATE TABLE PRODUCTS
(PROD_ID       VARCHAR2(10)     NOT NULL,
 VEND_ID       VARCHAR2(10)     NOT NULL,
 PRODUCT       VARCHAR2(30)     NOT NULL,
 COST              NUMBER(8,2)       NOT NULL,
PRIMARY KEY (PROD_ID, VEND_ID));

ALTER TABLE PRODUCTS
ADD CONSTRAINT PRODUCTS_PK PRIMARY KEY (PROD_ID, VEND_ID);

Unique Constraints

newterm_icon.gif

A unique column constraint in a table is similar to a primary key in that the value in that column for every row of data in the table must have a unique value. While a primary key constraint is placed on one column, you can place a unique constraint on another column even though it is not actually for use as the primary key.

Study the following example:

CREATE TABLE EMPLOYEE_TBL 
(EMP_ID        CHAR(9)        NOT NULL     PRIMARY KEY,
EMP_NAME       VARCHAR (40)   NOT NULL,
EMP_ST_ADDR    VARCHAR (20)   NOT NULL,
EMP_CITY       VARCHAR (15)   NOT NULL,
EMP_ST         CHAR(2)        NOT NULL,
EMP_ZIP        INTEGER(5)      NOT NULL,
EMP_PHONE      INTEGER(10)     NULL         UNIQUE,
EMP_PAGER      INTEGER(10)     NULL);

The primary key in this example is EMP_ID, meaning that the employee identification number is the column that is used to ensure that every record in the table is unique. The primary key is a column that is normally referenced in queries, particularly to join tables. The column EMP_PHONE has been designated as a UNIQUE value, meaning that no two employees can have the same telephone number. There is not a lot of difference between the two, except that the primary key is used to provide an order to data in a table and, in the same respect, join related tables.

Foreign Key Constraints

newterm_icon.gif

A foreign key is a column in a child table that references a primary key in the parent table. A foreign key constraint is the main mechanism used to enforce referential integrity between tables in a relational database. A column defined as a foreign key is used to reference a column defined as a primary key in another table.

Study the creation of the foreign key in the following example:

   mysql_icon.gif
CREATE TABLE EMPLOYEE_PAY_TBL
(EMP_ID           CHAR(9)        NOT NULL,
POSITION           VARCHAR2(15)   NOT NULL,
DATE_HIRE          DATE           NULL,
PAY_RATE           NUMBER(4,2)    NOT NULL,
DATE_LAST_RAISE    DATE           NULL,
CONSTRAINT EMP_ID_FK FOREIGN KEY (EMP_ID) REFERENCES EMPLOYEE_TBL (EMP_ID));

The EMP_ID column in this example has been designated as the foreign key for the EMPLOYEE_PAY_TBL table. This foreign key, as you can see, references the EMP_ID column in the EMPLOYEE_TBL table. This foreign key ensures that for every EMP_ID in the EMPLOYEE_PAY_TBL, there is a corresponding EMP_ID in the EMPLOYEE_TBL. This is called a parent/child relationship. The parent table is the EMPLOYEE_TBL table, and the child table is the EMPLOYEE_PAY_TBL table. Study Figure 3.2 for a better understanding of the parent table/child table relationship.

03fig02.gif

Figure 3.2 The parent/child table relationship.

In this figure, the EMP_ID column in the child table references the EMP_ID column in the parent table. In order for a value to be inserted for EMP_ID in the child table, there must first exist a value for EMP_ID in the parent table. Likewise, for a value to be removed for EMP_ID in the parent table, all corresponding values for EMP_ID must first be removed from the child table. This is how referential integrity works.

A foreign key can be added to a table using the ALTER TABLE command, as shown in the following example:

ALTER TABLE EMPLOYEE_PAY_TBL 
ADD CONSTRAINT ID_FK FOREIGN KEY (EMP_ID)
REFERENCES EMPLOYEE_TBL (EMP_ID);

NOT NULL Constraints

Previous examples use the keywords NULL and NOT NULL listed on the same line as each column and after the data type. NOT NULL is a constraint that you can place on a table's column. This constraint disallows the entrance of NULL values into a column; in other words, data is required in a NOT NULL column for each row of data in the table. NULL is generally the default for a column if NOT NULL is not specified, allowing NULL values in a column.

Using Check Constraints

Check (CHK) constraints can be utilized to check the validity of data entered into particular table columns. Check constraints are used to provide back-end database edits, although edits are commonly found in the front-end application as well. General edits restrict values that can be entered into columns or objects, whether within the database itself or on a front-end application. The check constraint is a way of providing another protective layer for the data.

The following example illustrates the use of a check constraint:

   mysql_icon.gif
CREATE TABLE EMPLOYEE_TBL
(EMP_ID        CHAR(9)        NOT NULL,
EMP_NAME       VARCHAR2(40)   NOT NULL,
EMP_ST_ADDR    VARCHAR2(20)   NOT NULL,
EMP_CITY       VARCHAR2(15)   NOT NULL,
EMP_ST         CHAR(2)        NOT NULL,
EMP_ZIP        NUMBER(5)      NOT NULL,
EMP_PHONE      NUMBER(10)     NULL,
EMP_PAGER      NUMBER(10)     NULL),
PRIMARY KEY (EMP_ID),
CONSTRAINT CHK_EMP_ZIP CHECK ( EMP_ZIP = '46234');

The check constraint in this table has been placed on the EMP_ZIP column, ensuring that all employees entered into this table have a ZIP code of '46234'. Perhaps that is a little restricting. Nevertheless, you can see how it works.

If you wanted to use a check constraint to verify that the ZIP code is within a list of values, your constraint definition could look like the following:

   mysql_icon.gif
CONSTRAINT CHK_EMP_ZIP CHECK ( EMP_ZIP in ('46234','46227','46745') );

If there is a minimum pay rate that can be designated for an employee, you could have a constraint that looks like the following:

   mysql_icon.gif
CREATE TABLE EMPLOYEE_PAY_TBL
(EMP_ID            CHAR(9)        NOT NULL,
POSITION           VARCHAR2(15)   NOT NULL,
DATE_HIRE          DATE           NULL,
PAY_RATE           NUMBER(4,2)    NOT NULL,
DATE_LAST_RAISE    DATE           NULL,
CONSTRAINT  EMP_ID_FK FOREIGN KEY (EMP_ID) REFERENCES EMPLOYEE_TBL (EMP_ID),
CONSTRAINT CHK_PAY CHECK ( PAY_RATE > 12.50 ) );

In this example, any employee entered in this table must be paid more than $12.50 an hour. You can use just about any condition in a check constraint, as you can with a SQL query. You learn more about these conditions in later hours.

Dropping Constraints

Any constraint that you have defined can be dropped using the ALTER TABLE command with the DROP CONSTRAINT option. For example, to drop the primary key constraint in the EMPLOYEES table, you can use the following command:

   mysql_icon.gif
   input_icon.gif

   ALTER TABLE EMPLOYEES DROP CONSTRAINT EMPLOYEES_PK;

   output_icon.gif
Table altered.

Some implementations may provide shortcuts for dropping certain constraints. For example, to drop the primary key constraint for a table in Oracle, you can use the following command:

   input_icon.gif

   ALTER TABLE EMPLOYEES DROP PRIMARY KEY;

   output_icon.gif
Table altered.

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.