Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Enable Disable Constraint

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 10

Oracle/PLSQL: Enable a foreign key

The syntax for enabling a foreign key is: ALTER TABLE table_name enable CONSTRAINT constraint_name;

For Example:
If you had created a foreign key as follows: CREATE TABLE supplier ( supplier_id numeric(10) not null, supplier_name varchar2(50) not null, contact_name varchar2(50), CONSTRAINT supplier_pk PRIMARY KEY (supplier_id) ); CREATE TABLE products ( product_id numeric(10) not null, supplier_id numeric(10) not null, CONSTRAINT fk_supplier FOREIGN KEY (supplier_id) REFERENCES supplier(supplier_id) ); In this example, we've created a primary key on the supplier table called supplier_pk. It consists of only one field - the supplier_id field. Then we've created a foreign key called fk_supplier on the products table that references the supplier table based on the supplier_id field.

If the foreign key had been disabled and we wanted to enable it, we could execute the following command: ALTER TABLE products enable CONSTRAINT fk_supplier; We have "alter table" syntax from Oracle to add data constraints in-place in this form:

alter table table_name add constraint constraint_name;

We can also use "alter table" syntax to enable or disable constraints:


alter table table_name ENABLE constraint constraint_name; alter table table_name DISABLE constraint constraint_name;

Check Constraint
We have details on the different types of constraints:
alter table table_name add constraint check_constraint_name CHECK (check_column_name IN ( 'check_constraint1_value', 'check_constraint2_value', 'check_constraint3_value', 'check_constraint4_value' ) ) DISABLE|ENABLE;

Here are some examples of Oracle "alter table" syntax to add foreign key constraints.
alter table cust_table add constraint fk_cust_name FOREIGN KEY (person_name) references person_table (person_name) initially deferred deferrable;

Here is an example of a multiple column foreign key constraint:


alter table cust_table add constraint fk_cust_name FOREIGN KEY (person_name, person_gender) references

person_table (person_name, person_gender) initially deferred deferrable;

Here is another example of Oracle "alter table" syntax to drop constraints.


ALTER TABLE cust_table drop constraint fk_cust_table_ref;

Here we use Oracle "alter table" syntax to add a check constraint.


alter table cust_table add constraint check_cust_types CHECK (cust_type IN ( 'yuppie', 'dink', 'guppie' ) );

Oracle Constraint Errors


The following errors are associated with Oracle constraint alter commands:
ORA-02290: check constraint (owner.constraintname) violated ORA-02291: integrity constraint (owner.constraintname) violated parent key not found

ORA-02292:violated integrity constraint (owner.constraintname)- child record found

Enabling and disabling Oracle constraints can be accomplished by using 1. Drop constraint command 2. Disable constraint command Constraints specified in the enable and disable clauses of a CREATE TABLE statement must be defined in the statement. Enabling and disabling Oracle constraints can also be done with the ENABLE and DISABLE keywords of the CONSTRAINT clause. If you define a constraint but do not explicitly enable or disable it, ORACLE enables it by default.

Any SQL INSERT, UPDATE or DELETE command applied to a table with constraints enabled has the possibility of failing. For example, updates applied to a Parent Table may fail if the statement leaves orphaned rows in a child table, INSERT command against a Child Table may fail if a matching foreign key value does not exist in the parent table. Constraint failures will result in the statement being rolled back - coding an application front end to deal with such errors is generally easier than handling all the business rules in code. You can design applications to use constraint data dictionary information to provide user feedback about integrity constraint violations. DROP Constraint command Drop an integrity constraint. Syntax: DROP PRIMARY KEY [CASCADE] DROP UNIQUE column [CASCADE] DROP CONSTRAINT constraint_name 'Column' can be either a single column name or several columns separated with commas, - DISABLE allow incoming data, regardless of whether it conforms to the constraint - VALIDATE ensure that existing data conforms to the constraint - NOVALIDATE existing data does not have to conform to the constraint These can be used in combination DISABLE { VALIDATE | NOVALIDATE } - DISABLE NOVALIDATE is the same as DISABLE. - DISABLE VALIDATE disables the constraint, drops the index on the constraint, and disallows any modification of the constrained columns. For a UNIQUE constraint, this enables you to load data from a nonpartitioned table into a partitioned table using the ALTER TABLE.. EXCHANGE PARTITION clause. When a unique or primary key is Enabled, if there is no existing index, a unique index is automatically created. When a unique or primary key is Disabled, the unique index is dropped.

When a constraint is Validated, all data must be checked. (this can be very slow.) The basic syntax for dropping a constraint is: alter table tablename drop constraint someconstraint; where tablename is the table name and someconstraint is the constraint name: For example: ALTER TABLE students DROP CONSTRAINT SYS_C001400; Drop constraind command implemented by using unix script If data migrations occur between databases, with the CONSTRAINTS=N clause missing, you end up with lots of duplicate check constraints. if [ ${column_name_next} = ${column_name} ] then echo "ALTER TABLE SYSADM.${table_name} DROP CONSTRAINT ${constraint_name_n ext};" >> ${TAB_NAME}_${ORACLE_SID}.sql Disable a constraint associated with a table: Syntax: DISABLE [[NO]VALIDATE] [UNIQUE] (column [,...] ) options [CASCADE] [{DROP| KEEP} INDEX] DISABLE [[NO]VALIDATE] PRIMARY KEY options [CASCADE] [{DROP|KEEP} INDEX] DISABLE [[NO]VALIDATE] [UNIQUE] CONSTRAINT constraint_name options [CASCADE] [{DROP|KEEP} INDEX] DISABLE ALL TRIGGERS Options: USING INDEX storage_options USING INDEX (create_index_statement) SORT | NOSORT LOCAL | GLOBAL PARTITION BY RANGE (column_list) (PARTITION partition VALUES LESS THAN (value [,value...]) EXCEPTIONS INTO [schema.]table storage_options:

PCTFREE int PCTUSED int INITTRANS int MAXTRANS int STORAGE storage_clause TABLESPACE tablespace LOGGING|NOLOGGING Disabling 'anonymous' constraint CREATE TABLE foo (bar NUMBER, baz NUMBER, UNIQUE (bar, baz)); ALTER TABLE foo DISABLE UNIQUE (bar, baz); Disabling named constraint CREATE TABLE foo (bar NUMBER, baz NUMBER, CONSTRAINT uq_foo UNIQUE (bar, baz)); ALTER TABLE foo DISABLE CONSTRAINT uq_foo; In addition to renaming tables and indexes Oracle9i Release 2 allows the renaming of columns and constraints on tables. In this example once the the TEST1 table is created it is renamed along with it's columns, primary key constraint and the index that supports the primary key: SQL> CREATE TABLE test1 ( 2 col1 NUMBER(10) NOT NULL, 3 col2 VARCHAR2(50) NOT NULL); Table created. SQL> ALTER TABLE test1 ADD ( 2 CONSTRAINT test1_pk PRIMARY KEY (col1)); Table altered. SQL> SELECT constraint_name 2 FROM user_constraints 3 WHERE table_name = 'TEST1' 4 AND constraint_type = 'P'; SQL> ALTER TABLE test RENAME CONSTRAINT test1_pk TO test_pk; Table altered.

SQL> ALTER INDEX test1_pk RENAME TO test_pk; Index altered.

SQL> SELECT constraint_name 2 FROM user_constraints 3 WHERE table_name = 'TEST' 4 AND constraint_type = 'P';

SQL> SELECT index_name, column_name 2 FROM user_ind_columns 3 WHERE table_name = 'TEST';

You can modify a constraint as follows :

Add new constraint to column or table. Remove constraint. Enable / disable constraint. You cannot change a constraint definition.

If we want to add a constraint to our new column we can use the following ALTER statement : ALTER TABLE book MODIFY(review NOT NULL); Note that we can't specify a constraint name with the above statement. If we wanted to further modify a constraint (other than enable / disable) we would have to drop the constraint and then re apply it specifying any changes. Assuming that we decide that 200 bytes is insufficient for our review field we might then want to increase its size.

The statement below demonstrates this : ALTER TABLE book MODIFY (review VARCHAR2(400)); We could not decrease the size of the column if the REVIEW column contained any data. ALTER TABLE book DISABLE CONSTRAINT b_auth; ALTER TABLE book ENABLE CONSTRAINT b_auth; The above statements demonstrate enabling and disabling Oracle constraints: Note that if, between disabling a constraint and re enabling it, data was entered to the table that included NULL values in the AUTHOR column, then you wouldn't be able to re enable the constraint. This is because the existing data would break the constraint integrity. You could update the column to replace NULL values with some default and then re enable the constraint. The syntax for enabling a unique constraint is: ALTER TABLE table_name ENABLE CONSTRAINT constraint_name; For example: ALTER TABLE supplier ENABLE CONSTRAINT supplier_unique; In this example, we're enabling a unique constraint on the supplier table called supplier_ unique. All tables will have full RI (Referential Integrity), including PK constraints, FK constraints and check constraints. The default for foreign key constraints will be "On Delete Restrict", unless otherwise specified. This means that no parent record can be deleted if there are corresponding child records. A referential column constraint with ON DELETE CASCADE will cascade deletes. Deleting a primary key row will delete all related foreign keys e.g. delete a customer and all that customer's orders will disappear. Careful with that one, please!

ntegrity Constraint States

You can specify that a constraint is enabled (ENABLE) or disabled (DISABLE). If a constraint is enabled, data is checked as it is entered or updated in the database, and data that does not conform to the constraint is prevented from being entered. If a constraint is disabled, then data that does not conform can be allowed to enter the database. Additionally, you can specify that existing data in the table must conform to the constraint (VALIDATE). Conversely, if you specify NOVALIDATE, you are not ensured that existing data conforms. An integrity constraint defined on a table can be in one of the following states:
ENABLE, VALIDATE ENABLE, NOVALIDATE DISABLE, VALIDATE DISABLE, NOVALIDATE

For details about the meaning of these states and an understanding of their consequences, see the Oracle Database SQL Language Reference. Some of these consequences are discussed here.

Disabling Constraints
To enforce the rules defined by integrity constraints, the constraints should always be enabled. However, consider temporarily disabling the integrity constraints of a table for the following performance reasons:

When loading large amounts of data into a table When performing batch operations that make massive changes to a table (for example, changing every employee's number by adding 1000 to the existing number) When importing or exporting one table at a time

In all three cases, temporarily disabling integrity constraints can improve the performance of the operation, especially in data warehouse configurations. It is possible to enter data that violates a constraint while that constraint is disabled. Thus, you should always enable the constraint after completing any of the operations listed in the preceding bullet list.

Enabling Constraints
While a constraint is enabled, no row violating the constraint can be inserted into the table. However, while the constraint is disabled such a row can be inserted. This row is known as an exception to the constraint. If the constraint is in the enable novalidated state, violations resulting from data entered while the constraint was disabled remain. The

rows that violate the constraint must be either updated or deleted in order for the constraint to be put in the validated state. You can identify exceptions to a specific integrity constraint while attempting to enable the constraint. See "Reporting Constraint Exceptions". All rows violating constraints are noted in an EXCEPTIONS table, which you can examine.

Enable Novalidate Constraint State


When a constraint is in the enable novalidate state, all subsequent statements are checked for conformity to the constraint. However, any existing data in the table is not checked. A table with enable novalidated constraints can contain invalid data, but it is not possible to add new invalid data to it. Enabling constraints in the novalidated state is most useful in data warehouse configurations that are uploading valid OLTP data. Enabling a constraint does not require validation. Enabling a constraint novalidate is much faster than enabling and validating a constraint. Also, validating a constraint that is already enabled does not require any DML locks during validation (unlike validating a previously disabled constraint). Enforcement guarantees that no violations are introduced during the validation. Hence, enabling without validating enables you to reduce the downtime typically associated with enabling a constraint.

Efficient Use of Integrity Constraints: A Procedure


Using integrity constraint states in the following order can ensure the best benefits: 1. 2. 3. 4. Disable state. Perform the operation (load, export, import). Enable novalidate state. Enable state.

Some benefits of using constraints in this order are:

You might also like