Table of Contents |
2.4 ConstraintsConstraints allow you to automatically enforce the integrity of data and to filter the data that is placed in a database. In a sense, constraints are rules that define which data values are valid during INSERT, UPDATE, and DELETE operations. When a data modification transaction breaks the rules of a constraint, the transaction is rejected. In the ANSI standard, there are four constraint types: CHECK, PRIMARY KEY, UNIQUE, and FOREIGN KEY. (The RDBMS platforms may allow more. Refer to different platform sections of the CREATE/ALTER TABLE Statement to find out these exceptions.) 2.4.1 ScopeConstraints may be applied at the column-level or the table-level:
2.4.2 SyntaxConstraints are defined when you create or alter a table. The general syntax for constraints is shown here: CONSTRAINT [constraint_name] constraint_type [(column [,...])] [predicate] [constraint_deferment] [deferment_timing] The syntax elements are as follows:
Note that the vendor platforms may have some variations on this syntax. Check different platform sections of CREATE/ALTER TABLE Statement for more details. 2.4.3 PRIMARY KEY ConstraintsA PRIMARY KEY constraint declares one or more columns whose values uniquely identify each record in the table. It is considered a special case of the UNIQUE constraint. Some rules about primary keys:
The following ANSI standard code includes the options for creating both a table- and column-level primary key constraint on a table called distributors. The first example shows a column-level primary-key constraint, while the second shows a table-level constraint: -- Creating a column-level constraint CREATE TABLE distributors (dist_id CHAR(4) NOT NULL PRIMARY KEY, dist_name VARCHAR(40), dist_address1 VARCHAR(40), dist_address2 VARCHAR(40), city VARCHAR(20), state CHAR(2) , zip CHAR(5) , phone CHAR(12) , sales_rep INT ); -- Creating a table-level constraint CREATE TABLE distributors (dist_id CHAR(4) NOT NULL, dist_name VARCHAR(40), dist_address1 VARCHAR(40), dist_address2 VARCHAR(40), city VARCHAR(20), state CHAR(2) , zip CHAR(5) , phone CHAR(12) , sales_rep INT , CONSTRAINT pk_dist_id PRIMARY KEY (dist_id)); In the example showing a table-level primary key, we could easily have created a concatenated key by listing several columns separated by commas between each one. 2.4.4 FOREIGN KEY ConstraintsA FOREIGN KEY constraint defines one or more columns in the table as referencing columns to a UNIQUE or PRIMARY KEY in another table. (A foreign key can reference a unique or primary key in the same table as the foreign key itself, but such foreign keys are rare.) Foreign keys can then prevent the entry of data into a table where there is no matching value in the related table. They are the primary means of identifying the relationship between tables in a relational database. Some rules about foreign keys:
The full SQL2003 syntax for foreign keys is more elaborate than the general syntax for constraints shown earlier, and is dependent on whether you are making a table-level or column-level declaration: -- Table-level foreign key [CONSTRAINT [constraint_name] ] FOREIGN KEY (local_column [,...] ) REFERENCES referenced_table [ (referenced_column [,...]) ] [MATCH {FULL | PARTIAL | SIMPLE} ] [ON UPDATE {NO ACTION | CASCADE | RESTRICT | SET NULL | SET DEFAULT} ] [ON DELETE {NO ACTION | CASCADE | RESTRICT | SET NULL | SET DEFAULT} ] [constraint_deferment] [deferment_timing] -- Column-level foreign key [CONSTRAINT [constraint_name] ] REFERENCES referenced_table [ (referenced_column [,...]) ] [MATCH {FULL | PARTIAL | SIMPLE} ] [ON UPDATE {NO ACTION | CASCADE | RESTRICT | SET NULL | SET DEFAULT} ] [ON DELETE {NO ACTION | CASCADE | RESTRICT | SET NULL | SET DEFAULT} ] [constraint_deferment] [deferment_timing] Keywords common to a standard constraint declaration are described above, under the "Syntax" section. Keywords specific to foreign keys are described in the following list:
As with the code example for primary keys, you can adapt this generic syntax to both column-level and table-level foreign key constraints. Note that column-level and table-level constraints perform their function in exactly the same way. They are merely defined at different levels of the CREATE TABLE command. In the following example, we create a single-column foreign key on the salesrep column referencing the empid column of the employee table. We create the foreign key two different ways, the first time at the column level, the second time at the table level: -- Creating a column-level constraint CREATE TABLE distributors (dist_id CHAR(4) PRIMARY KEY, dist_name VARCHAR(40), dist_address1 VARCHAR(40), dist_address2 VARCHAR(40), city VARCHAR(20), state CHAR(2) , zip CHAR(5) , phone CHAR(12) , sales_rep INT NOT NULL REFERENCES employee(empid)); -- Creating a table-level constraint CREATE TABLE distributors (dist_id CHAR(4) NOT NULL, dist_name VARCHAR(40), dist_address1 VARCHAR(40), dist_address2 VARCHAR(40), city VARCHAR(20), state CHAR(2) , zip CHAR(5) , phone CHAR(12) , sales_rep INT , CONSTRAINT pk_dist_id PRIMARY KEY (dist_id), CONSTRAINT fk_empid FOREIGN KEY (sales_rep) REFERENCES employee(empid)); 2.4.5 UNIQUE ConstraintsA UNIQUE constraint, sometimes called a candidate key, declares that the values in one column, or the combination of values in more than one column, must be unique. Rules concerning unique constraints include:
In the following example, we limit the number of distributors we do business with to only one distributor per ZIP Code. We also allow one (and only one) "catch-all" distributor with a NULL ZIP Code. This functionality can be implemented easily using a UNIQUE constraint, either at the column or the table level: -- Creating a column-level constraint CREATE TABLE distributors (dist_id CHAR(4) PRIMARY KEY, dist_name VARCHAR(40), dist_address1 VARCHAR(40), dist_address2 VARCHAR(40), city VARCHAR(20), state CHAR(2) , zip CHAR(5) UNIQUE , phone CHAR(12) , sales_rep INT NOT NULL REFERENCES employee(empid)); -- Creating a table-level constraint CREATE TABLE distributors (dist_id CHAR(4) NOT NULL, dist_name VARCHAR(40), dist_address1 VARCHAR(40), dist_address2 VARCHAR(40), city VARCHAR(20), state CHAR(2) , zip CHAR(5) , phone CHAR(12) , sales_rep INT , CONSTRAINT pk_dist_id PRIMARY KEY (dist_id), CONSTRAINT fk_emp_id FOREIGN KEY (sales_rep) REFERENCES employee(empid), CONSTRAINT unq_zip UNIQUE (zip) ); 2.4.6 CHECK ConstraintsCHECK constraints allow you to perform comparison operations to ensure that values match specific conditions that you set out. The syntax for a check constraint is very similar to the general syntax for constraints: [CONSTRAINT] [constraint_name] CHECK (search_conditions) [constraint_deferment] [deferment_timing] Other elements of the constraint are introduced earlier in this section. The following element is unique to the CHECK constraint:
A check constraint is considered matched when the search conditions evaluate to TRUE or UNKNOWN. Check constraints are limited to Boolean operations (e.g., =, >=, <=, or <>), though they may include any SQL2003 predicates such as IN or LIKE. Check constraints may be appended to one another (when checking a single column) using the AND and OR operators. Some other rules about CHECK constraints:
The following example adds a check constraint to the dist_id and zip columns. (This example uses generic code run on SQL Server.) The ZIP Code must fall into the normal ranges for postal ZIP Codes, while the dist_id values are allowed to contain either four alphabetic characters or two alphabetic and two numeric characters: -- Creating column-level CHECK constraints CREATE TABLE distributors (dist_id CHAR(4) CONSTRAINT pk_dist_id PRIMARY KEY CONSTRAINT ck_dist_id CHECK (dist_id LIKE '[A-Z][A-Z][A-Z][A-Z]' OR dist_id LIKE '[A-Z][A-Z][0-9][0-9]'), dist_name VARCHAR(40), dist_address1 VARCHAR(40), dist_address2 VARCHAR(40), city VARCHAR(20), state CHAR(2) CONSTRAINT def_st DEFAULT ("CA"), zip CHAR(5) CONSTRAINT unq_dist_zip UNIQUE CONSTRAINT ck_dist_zip CHECK (zip LIKE '[0-9][0-9][0-9][0-9][0-9]'), phone CHAR(12), sales_rep INT NOT NULL DEFAULT USER REFERENCES employee(emp_id)) |
Table of Contents |