April 17th, 2009

How do Constraints Work?

Posted by admin in P. Table Creation

Constraints allow you to write rules for the allowable values in columns and enforce the integrity of the data. As you can see, there are two types of constraints in the format of a CREATE TABLE statement:

          CREATE TABLE table_name
                (column_name1 data_type1 [col_constraint1],
                 column_name2 data_type2 [col_constraint2],
                 ...
                [CONSTRAINT constraint_name1 table_constraint1,]
                [CONSTRAINT constraint_name2 table_constraint2,]
                 ...);

A column constraint is in the column definition and sets conditions only on the values in this column.
A column constraint does not have an explicit constraint name and can not apply to more than one column.
(The DBMS system assigns a column constraint name consisting of random characters and numbers.)

A table constraint is defined separately from the column definitions and can set conditions on one or many columns in the table.

Only table constraints have constraint names, but a column constraint (one column) can be stated as a table constraint and given a name. This allows you to ALTER or DROP the constraint by name.
Many company standards only allow named table constraints, not column constraints, so that the constraint can be identified in warning and error messages.
The exception is NOT NULL, which is nearly always an unnamed column constraint.

A primary key can be defined as a column constraint (if it is one column) or a table constraint.

Comments are closed.

Sorry, the comment form is closed at this time.