Oracle Database enables you to apply constraints both at the table and column level. A constraint specified as part of the definition of a column or attribute is an inline specification. A constraint specified as part of the table definition is an out-of-line specification.
The term key is used in the definitions of several types of integrity constraints. A key is the column or set of columns included in the definition of certain types of integrity constraints. Keys describe the relationships between the tables and columns of a relational database. Individual values in a key are called key values.
Table 5-1 describes the types of constraints. Each can be specified either inline or out-of-line, except for NOT NULL, which must be inline.
Constraint Type | Description | See Also |
---|---|---|
NOT NULL |
Allows or disallows inserts or updates of rows containing a null in a specified column. |
"NOT NULL Integrity Constraints" |
Unique key |
Prohibits multiple rows from having the same value in the same column or combination of columns but allows some values to be null. |
"Unique Constraints" |
Primary key |
Combines a NOT NULL constraint and a unique constraint. It prohibits multiple rows from having the same value in the same column or combination of columns and prohibits values from being null. |
"Primary Key Constraints" |
Foreign key |
Designates a column as the foreign key and establishes a relationship between the foreign key and a primary or unique key, called the referenced key. |
"Foreign Key Constraints" |
Check |
Requires a database value to obey a specified condition. |
"Check Constraints" |
REF |
Dictates types of data manipulation allowed on values in a REF column and how these actions affect dependent values. In an object-relational database, a built-in data type called a REF encapsulates a reference to a row object of a specified object type. Referential integrity constraints on REFcolumns ensure that there is a row object for the REF. |
Oracle Database Object-Relational Developer's Guide to learn about REF constraints |
A NOT NULL constraint requires that a column of a table contain no null values. A null is the absence of a value. By default, all columns in a table allow nulls.
NOT NULL constraints are intended for columns that must not lack values. For example, the hr.employees table requires a value in the last_name column. An attempt to insert an employee row without a last name generates an error:
SQL> INSERT INTO hr.employees (employee_id, last_name) values (999, 'Smith'); . . . ERROR at line 1: ORA-01400: cannot insert NULL into ("HR"."EMPLOYEES"."LAST_NAME")
You can only add a column with a NOT NULL constraint if the table does not contain any rows or if you specify a default value.
A unique key constraint requires that every value in a column or set of columns be unique. No rows of a table may have duplicate values in a single column (the unique key) or set of columns (the composite unique key) with a unique key constraint.
Note:
The term key refers only to the columns defined in the integrity constraint. Because the database enforces a unique constraint by implicitly creating or reusing an index on the key columns, the term unique key is sometimes incorrectly used as a synonym for unique key constraint or unique index.
Unique key constraints are appropriate for any column where duplicate values are not allowed. Unique constraints differ from primary key constraints, whose purpose is to identify each table row uniquely, and typically contain values that have no significance other than being unique. Examples of unique keys include:
As shown in Example 2-1, a unique key constraint exists on the email column of the hr.employees table. The relevant part of the statement is as follows:
CREATE TABLE employees ( ... , email VARCHAR2(25) CONSTRAINT emp_email_nn NOT NULL ... , CONSTRAINT emp_email_uk UNIQUE (email) ... );
The emp_email_uk constraint ensures that no two employees have the same email address, as shown in Example 5-1.
SQL> SELECT employee_id, last_name, email FROM employees WHERE email = 'PFAY'; EMPLOYEE_ID LAST_NAME EMAIL ----------- ------------------------- ------------------------- 202 Fay PFAY SQL> INSERT INTO employees (employee_id, last_name, email, hire_date, job_id) 1 VALUES (999,'Fay','PFAY',SYSDATE,'ST_CLERK'); . . . ERROR at line 1: ORA-00001: unique constraint (HR.EMP_EMAIL_UK) violated
Unless a NOT NULL constraint is also defined, a null always satisfies a unique key constraint. Thus, columns with both unique key constraints and NOT NULL constraints are typical. This combination forces the user to enter values in the unique key and eliminates the possibility that new row data conflicts with existing row data.
Note:
Because of the search mechanism for unique key constraints on multiple columns, you cannot have identical values in the non-null columns of a partially null composite unique key constraint.
In a primary key constraint, the values in the group of one or more columns subject to the constraint uniquely identify the row. Each table can have one primary key, which in effect names the row and ensures that no duplicate rows exist.
A primary key can be natural or a surrogate. A natural key is a meaningful identifier made of existing attributes in a table. For example, a natural key could be a postal code in a lookup table. In contrast, a surrogate key is a system-generated incrementing identifier that ensures uniqueness within a table. Typically, a sequence generates surrogate keys.
The Oracle Database implementation of the primary key constraint guarantees that the following statements are true:
A typical situation calling for a primary key is the numeric identifier for an employee. Each employee must have a unique ID. A employee must be described by one and only one row in the employees table.
Example 5-1 indicates that an existing employee has the employee ID of 202, where the employee ID is the primary key. The following example shows an attempt to add an employee with the same employee ID and an employee with no ID:
SQL> INSERT INTO employees (employee_id, last_name, email, hire_date, job_id) 1 VALUES (202,'Chan','ICHAN',SYSDATE,'ST_CLERK'); . . . ERROR at line 1: ORA-00001: unique constraint (HR.EMP_EMP_ID_PK) violated SQL> INSERT INTO employees (last_name) VALUES ('Chan'); . . . ERROR at line 1: ORA-01400: cannot insert NULL into ("HR"."EMPLOYEES"."EMPLOYEE_ID")
The database enforces primary key constraints with an index. Usually, a primary key constraint created for a column implicitly creates a unique index and a NOT NULL constraint. Note the following exceptions to this rule:
Note:
You can explicitly create a unique index with the CREATE UNIQUE INDEX statement.
By default the name of the implicitly created index is the name of the primary key constraint. You can also specify a user-defined name for an index. You can specify storage options for the index by including the ENABLE clause in the CREATE TABLE or ALTER TABLE statement used to create the constraint.
Whenever two tables contain one or more common columns, Oracle Database can enforce the relationship between the two tables through a foreign key constraint, also called a referential integrity constraint. The constraint requires that for each value in the column on which the constraint is defined, the value in the other specified other table and column must match. An example of a referential integrity rule is an employee can work for only an existing department.
Table 5-2 lists terms associated with referential integrity constraints.
Term | Definition |
---|---|
Foreign key |
The column or set of columns included in the definition of the constraint that reference a referenced key. For example, the department_id column in employees is a foreign key that references the department_id column in departments. Foreign keys may be defined as multiple columns. However, a composite foreign key must reference a composite primary or unique key with the same number of columns and the same data types. The value of foreign keys can match either the referenced primary or unique key value, or be null. If any column of a composite foreign key is null, then the non-null portions of the key do not have to match any corresponding portion of a parent key. |
Referenced key |
The unique key or primary key of the table referenced by a foreign key. For example, the department_id column in departments is the referenced key for the department_id column in employees. |
Dependent or child table |
The table that includes the foreign key. This table depends on the values present in the referenced unique or primary key. For example, the employees table is a child of departments. |
Referenced or parent table |
The table that is referenced by the foreign key of the child table. It is this table's referenced key that determines whether specific inserts or updates are allowed in the child table. For example, the departments table is a parent of employees. |
Figure 5-1 shows a foreign key on the employees.department_id column. It guarantees that every value in this column must match a value in the departments.department_id column. Thus, no erroneous department numbers can exist in the employees.department_id column.
Figure 5-2 shows a self-referential integrity constraint in which a foreign key references a parent key in the same table. The constraint ensures that every value in the employees.manager_id column corresponds to an existing value in the employees.employee_id column. For example, the manager for employee 102 must exist in the employees table. This constraint eliminates the possibility of erroneous employee numbers in the manager_id column.
The relational model permits the value of foreign keys to match either the referenced primary or unique key value, or be null. For example, a user could insert a row into hr.employees without specifying a department ID.
If any column of a composite foreign key is null, then the non-null portions of the key do not have to match any corresponding portion of a parent key.
The relationship between foreign key and parent key has implications for deletion of parent keys. For example, if a user attempts to delete the record for this department, then what happens to the records for employees in this department?
When a parent key is modified, referential integrity constraints can specify the following actions to be performed on dependent rows in a child table:
In the normal case, users cannot modify referenced key values if the results would violate referential integrity. For example, if employees.department_id is a foreign key to departments, and if employees belong to a particular department, then an attempt to delete the row for this department violates the constraint.
A deletion cascades (DELETE CASCADE) when rows containing referenced key values are deleted, causing all rows in child tables with dependent foreign key values to also be deleted. For example, the deletion of a row in departments causes rows for all employees in this department to be deleted.
A deletion sets null (DELETE SET NULL) when rows containing referenced key values are deleted, causing all rows in child tables with dependent foreign key values to set those values to null. For example, the deletion of a department row sets the department_id column value to null for employees in this department.
Table 5-3 outlines the DML statements allowed by the different referential actions on the key values in the parent table, and the foreign key values in the child table.
DML Statement | Issued Against Parent Table | Issued Against Child Table |
---|---|---|
INSERT |
Always OK if the parent key value is unique |
OK only if the foreign key value exists in the parent key or is partially or all null |
>UPDATE NO ACTION |
Allowed if the statement does not leave any rows in the child table without a referenced parent key value |
Allowed if the new foreign key value still references a referenced key value |
DELETE NO ACTION |
Allowed if no rows in the child table reference the parent key value |
Always OK |
DELETE CASCADE |
Always OK |
Always OK |
DELETE SET NULL |
Always OK |
Always OK |
Note:
Other referential actions not supported by FOREIGN KEY integrity constraints of Oracle Database can be enforced using database triggers. See "Overview of Triggers".
As a rule, foreign keys should be indexed. The only exception is when the matching unique or primary key is never updated or deleted. Indexing the foreign keys in child tables provides the following benefits:
A check constraint on a column or set of columns requires that a specified condition be true or unknown for every row. If DML results in the condition of the constraint evaluating to false, then the SQL statement is rolled back.
The chief benefit of check constraints is the ability to enforce very specific integrity rules. For example, you could use check constraints to enforce the following rules in the hr.employees table:
The following example creates a maximum salary constraint on employees and demonstrates what happens when a statement attempts to insert a row containing a salary that exceeds the maximum:
SQL> ALTER TABLE employees ADD CONSTRAINT max_emp_sal CHECK (salary < 10001); SQL> INSERT INTO employees (employee_id,last_name,email,hire_date,job_id,salary) 1 VALUES (999,'Green','BGREEN',SYSDATE,'ST_CLERK',20000); . . . ERROR at line 1: ORA-02290: check constraint (HR.MAX_EMP_SAL) violated
A single column can have multiple check constraints that reference the column in its definition. For example, the salary column could have one constraint that prevents values over 10000 and a separate constraint that prevents values less than 500.
If multiple check constraints exist for a column, then they must be designed so their purposes do not conflict. No order of evaluation of the conditions can be assumed. The database does not verify that check conditions are not mutually exclusive.
States of Integrity Constraints >>