SQL Integrity Constraints
SQL Integrity Constraints
Integrity Constraints are used to apply business rules for the database tables.
The constraints available in SQL are Foreign Key, Not Null, Unique, Check.
column_name1, column_name2 are the names of the columns which define the primary
Key.
The syntax within the bracket i.e. [CONSTRAINT constraint_name] is optional.
For Example: To create an employee table with Primary Key constraint, the query would be
like.
or
For Example:
2) If the employee table has a 'mgr_id' i.e, manager id as a foreign key which references primary
key 'id' within the same table, the query would be like,
For Example: To create a employee table with Null value, the query would be like
For Example: To create an employee table with Unique key, the query would be like,
or
For Example: In the employee table to select the gender of a person, the query would be like
Constraint types
There are five integrity constraints in Oracle.
Not Null
A column in a table can be specified not null. It's not possible to insert a null in such a column. The
default is null. So, in the following create table statement, a null can be inserted into the column named
c.
Unique Key
The unique constraint doesn't allow duplicate values in a column. If the unique constraint encompasses
two or more columns, no two equal combinations are allowed.
In order to remove that constraint, an alter table ... drop constraint ... is needed:
Primary Key
On a technical level, a primary key combines a unique and a not null constraint. Additionally, a table can
have at most one primary key. After creating a primary key, it can be referenced by a foreign key.
Foreign Key
A foreign key constraint (also called referential integrity constraint) on a column ensures that the value
in that column is found in the primary key of another table.
If a table has a foreign key that references a table, that referenced table can be dropped with a drop
table .. cascade constraints.
It is not possible to establish a foreign key on a global temporary table. If tried, Oracle issues a ORA-
14455: attempt to create referential integrity constraint on temporary table.
Check
A check constraint allows to state a minimum requirement for the value in a column. If more
complicated requirements are desired, an insert trigger must be used.
The following table allows only numbers that are between 0 and 100 in the column a;
Disabling Constraints
Disabling 'anonymous' constraint
create table foo (bar number, baz number, unique (bar, baz));
alter table foo disable unique (bar, baz);
Data dictionary
Oracle stores the definitions of integrity constraints in the data dictionary.
Thanks
Thanks to Kieron Bird who notified me of an error on this page and Jim Davis who spotted a typo.