Data integrity guarantees that data adheres to business rules. There are three primary ways achiveing this:
In this section, we focus on the integrity constraints.
An integrity constraint can be enabled or disabled, validated or non-validated over existing data (for the purpose of constraint violation checking) which are created before the enabling of constraint.
Primary key and unique key constraints are enforced using indexes (creating index is covered in the chapter on managing indexes). If a constraint is enabled, oracle will create a unique index on the constraint column if the index does not unique, or reuse the existing index.
Foreign key constraint prevents the incorrect manipulation of data references. For example, the DEPARTMENT_ID column in an EMPLOYEE table refers to a parent table DEPARTMENT. A foreign key constraint on DEPARTMENT_ID referring to DEPARTMENT table can prevent us from 1) inserting a new record into EMPLOYEE with a non-existing DEPARTMENT_ID; 2) deleting a record in DEPARTMENT table whose DEPARTMENT_ID value is used in EMPLOYEE table.
Constraints can be created in-line or out-of-line.
For example:
CREATE TABLE employee (
id NUMBER(7) CONSTRAINT employee_id_pk PRIMARY KEY,
name VARCHAR2(50) CONSTRAINT name_nn NOT NULL,
dept_id NUMBER(7));
For example:
ALTER TABLE employee
ADD (CONSTRAINT employee_dept_id_fk FOREIGN KEY (dept_id)
REFERENCES department (id));
A constraint that is currently disabled can be disabled in one of the two ways: enable NOVALIDATE or enable VALIDATE. The former does not check existing data for constraint violation.
The simplified syntax is:
ALTER TABLE <table name>
ENABLE NOVALIDATE|VALIDATE {CONSTRAINT <constraint name> | PRIMARY KEY | UNIQUE (column)}
For example, assuming the primary key is not defined for table EMPLOYEE.
SQL> ALTER TABLE employee ENABLE VALIDATE emp_dept_id_fk;
SQL> ALTER TABLE employee ENABLE VALIDATE PRIMARY KEY (id);
OR
SQL> ALTER TABLE employee ENABLE NOVALIDATE emp_dept_id_fk;