Constraints Maintenance

Adding Constraints to a table:
Ø  A constraint can be added to a table at any time after the table was created by using alter table statement, using ADD clause.
            Alter Table <TableName>
            Add [Contraint <ConstraintName>]
The Constraint name in the syntax is optional, but recommended.
Ø  We can ADD, DROP, ENABLE or DISABLE a constraint, but cannot modify the physical structure of the table.
Ø  A NOT NULL can be added to existing column by using the modify clause of the ALTER table statement.
Ø  NOT NULL can be defined only when the table contains no rows.
·         Alter Table Emp Add Constraint Emp_mgr_fk Foreign key(mgr) References Emp(Empno);
Dropping Constraints:
Ø  To Drop a constraint identity the constraint the constraint name from the
o   USER_CONS_COLUMNS data dictionary views.
Ø  The ALTER TABLE statement is used with the drop clause.
Ø  The CASCADE option of the DROP Clause causes any dependent constraints also to be dropped.
Ø  When a constraint is dropped, the constraint is no longer enforced and is no longer available in the data dictionary.
·         Alter Table <Table_Name>

            PRIMARY KEY/UNIQUE (column)/
            CONSTRAINT ConstraintName[CASCADE];
·         Alter Table Dept drop primary key cascade;
·         Alter Table Emp drop constraint Emp_Mgr_FK;
Enabling Constraints:
Ø  The constraint can be enabled without dropping in or re-creating it.
Ø  The alter table statement with the enable clause is used for the purpose.
·         Alter Table <TableName>
                  Enable Constraint <ConstraintName>;
Ø  Enabling a constraint applies to all the data in the table at a time.
Ø  When an UNIQUE or Primary key constraint is ENABLED, the UNIQUE or Primary key index is automatically created.
Ø  The ENABLE clause can be used both in create table as well as alter table statements.
·         Alter Table Emp ENABLE Constraint Emp_Empno_FK;
Viewing Constraints:
Ø  To view all constraints on a table query upon the data dictionary USER_CONSTRAINTS.
Ø  The Codes that are revealed are …
            C à CHECK
            P à PRIMARY KEY
            U à UNIQUE KEY
·         Select Constraint_name, Constraint_type,Search_condtion From USER_CONSTRAINTS where table_name = ‘EMP’;
Viewing the columns Associated with Constraints:
Ø  The Names of the columns that are involved in constraints can be known by querying the USER_CONS_COLUMNS data dictionary view.

·         Select  constraint_name, column_name from user_cons_columns where table_name =’EMP’;