Sub topic 12
Adding and dropping constraints with ALTER TABLE
This chapter assumes you can write CREATE TABLE with inline and out-of-line constraints and give constraints explicit names. It also assumes you have the departments and employees tables from the earlier chapters in an Oracle Database 12c or later schema.
Tables rarely stay fixed. Requirements change, and a rule you left out of CREATE TABLE has to be added later, often to a table that already holds data. ALTER TABLE adds, renames, and drops constraints without recreating the table. The main difficulty is that Oracle checks existing rows when you add a rule.
Adding constraints
The basic form is ALTER TABLE ... ADD CONSTRAINT name definition. The definition uses the same syntax as an out-of-line constraint in CREATE TABLE.
ALTER TABLE employees ADD (phone VARCHAR2(20));
ALTER TABLE employees ADD CONSTRAINT employees_phone_uk
UNIQUE (phone);
ALTER TABLE employees ADD CONSTRAINT employees_hire_ck
CHECK (hire_date >= DATE '1990-01-01');
ALTER TABLE employees ADD CONSTRAINT employees_manager_fk
FOREIGN KEY (manager_id) REFERENCES employees (employee_id)
DEFERRABLE INITIALLY DEFERRED;The first statement adds a column. The next three add a unique, a check, and a self-referencing foreign key. The foreign key needs a manager_id column, which the series added earlier with ALTER TABLE employees ADD (manager_id NUMBER). A UNIQUE constraint allows multiple NULL values, so employees_phone_uk does not reject the rows where phone is still empty.
You can add several constraints in one statement by wrapping them in parentheses:
ALTER TABLE departments ADD (
CONSTRAINT departments_name_len_ck CHECK (LENGTH(department_name) >= 2),
CONSTRAINT departments_name_trim_ck CHECK (department_name = TRIM(department_name))
);If one definition fails, the whole statement fails and none of them is added.
Each constraint type has an ADD form:
| Constraint | ADD syntax |
|---|---|
| PRIMARY KEY | `ADD CONSTRAINT n PRIMARY KEY (cols)` |
| UNIQUE | `ADD CONSTRAINT n UNIQUE (cols)` |
| CHECK | `ADD CONSTRAINT n CHECK (condition)` |
| FOREIGN KEY | `ADD CONSTRAINT n FOREIGN KEY (cols) REFERENCES parent (cols) [ON DELETE ...]` |
| NOT NULL | `MODIFY (col [CONSTRAINT n] NOT NULL)` |
NOT NULL is the exception. Oracle treats it as a property of the column, so you add it with MODIFY:
ALTER TABLE employees MODIFY (phone CONSTRAINT employees_phone_nn NOT NULL);To make a column optional again, use MODIFY (phone NULL), or drop the named constraint.
What happens to existing rows
By default a new constraint is created as ENABLE VALIDATE. Oracle enables it for future changes and also checks every existing row. If any row violates the rule, the statement fails and the constraint is not created.
The diagram shows the decision path.
The error depends on the constraint type:
| Error | Cause |
|---|---|
| ORA-02437 | Cannot validate the primary key. Duplicate values exist. |
| ORA-02299 | Cannot validate a unique constraint. Duplicate keys exist. |
| ORA-02293 | Cannot validate a check constraint. A row violates the condition. |
| ORA-02298 | Cannot validate a foreign key. A child row has no matching parent key. |
| ORA-02296 | Cannot enable a `NOT NULL` constraint. Null values exist. |
| ORA-02264 | The constraint name is already used by another constraint in the schema. |
Constraint names must be unique within a schema, not just within a table. This is one reason a naming convention that includes the table name, such as employees_phone_uk, is worth the typing.
Finding the offending rows
Before you add a constraint, run a query that looks for violations. The query depends on the rule:
-- Duplicates that would break a UNIQUE or PRIMARY KEY on email
SELECT email, COUNT(*) AS copies
FROM employees
GROUP BY email
HAVING COUNT(*) > 1;
-- Orphans that would break a FOREIGN KEY on department_id
SELECT e.employee_id, e.department_id
FROM employees e
WHERE e.department_id IS NOT NULL
AND NOT EXISTS (SELECT 1
FROM departments d
WHERE d.department_id = e.department_id);
-- Rows that would break a CHECK on salary
SELECT employee_id, salary
FROM employees
WHERE NOT (salary >= 0);Note the IS NOT NULL test in the orphan query. A foreign key ignores rows where any key column is NULL, so the query should too. The last query uses NOT (...) and not salary < 0. A check constraint passes when its condition evaluates to UNKNOWN, which happens for a null salary, and NOT (salary >= 0) is also UNKNOWN for a null salary, so the query skips those rows the same way the constraint does.
For large tables, Oracle can record the violating rowids for you with EXCEPTIONS INTO. You first create an exceptions table by running the utlexpt1.sql script shipped with the database.
ALTER TABLE employees ADD CONSTRAINT employees_email_uk
UNIQUE (email) EXCEPTIONS INTO exceptions;The statement still fails, but the exceptions table now lists the rowids of the rows that caused the failure.
Constraint names and what a missing name costs you
If you omit CONSTRAINT name, Oracle generates a name such as SYS_C0012345. That name differs between databases, so a script that drops it by name works in development and fails in production. Name every constraint you add.
You can rename a constraint without touching the data:
ALTER TABLE employees RENAME CONSTRAINT sys_c0012345 TO employees_dept_nn;Renaming is a metadata change. It is quick and does not revalidate rows.
Dropping constraints
Dropping by name works for every constraint type:
ALTER TABLE employees DROP CONSTRAINT employees_hire_ck;Primary and unique keys also have shortcuts that name the columns and not the constraint:
ALTER TABLE departments DROP PRIMARY KEY;
ALTER TABLE employees DROP UNIQUE (phone);Use the shortcuts only in throwaway scripts. DROP CONSTRAINT name states exactly what is removed, and the shortcut forms cannot be used when you have several unique constraints on the same columns.
Dependent foreign keys
You cannot drop a primary or unique key that a foreign key references. Oracle raises ORA-02273. Add CASCADE to drop the dependent foreign keys in the same statement:
ALTER TABLE departments DROP CONSTRAINT departments_pk CASCADE;The index behind a key
A primary or unique constraint is enforced by an index. If Oracle created the index along with the constraint, dropping the constraint drops the index too. If you created the index yourself before adding the constraint, the index stays. You can override both defaults:
ALTER TABLE employees DROP CONSTRAINT employees_email_uk KEEP INDEX;
ALTER TABLE employees DROP CONSTRAINT employees_email_uk DROP INDEX;Without the index, uniqueness is no longer enforced, but queries that used the index keep their speed with KEEP INDEX.
Dropping a column
A column that appears in a constraint with other columns cannot be dropped alone. A column in a multi-column constraint or referenced by a foreign key fails with an error. DROP COLUMN ... CASCADE CONSTRAINTS removes the column and every constraint that involves it:
ALTER TABLE employees DROP COLUMN phone CASCADE CONSTRAINTS;Changing a constraint
Oracle does not let you edit a CHECK condition, the columns of a key, or the ON DELETE action of a foreign key. To change them, drop the constraint and add a new one. Do this in a maintenance window or inside one script, because between the two statements the rule is not enforced.
ALTER TABLE employees DROP CONSTRAINT employees_status_ck;
ALTER TABLE employees ADD CONSTRAINT employees_status_ck
CHECK (status IN ('ACTIVE', 'INACTIVE', 'ON_LEAVE'));What you can change in place is the constraint state. You can disable a constraint without losing its definition, and re-enable it later:
ALTER TABLE employees DISABLE CONSTRAINT employees_manager_fk;
ALTER TABLE employees ENABLE CONSTRAINT employees_manager_fk;Re-enabling validates the whole table by default. The final chapter of this tutorial covers the states ENABLE, DISABLE, VALIDATE, NOVALIDATE, and DEFERRABLE in detail.
Operational points
- Every
ALTER TABLEis DDL. It commits the current transaction before and after it runs, so you cannot roll it back. - Adding or enabling a validated constraint reads the whole table and takes a lock. On a busy production table, run it when traffic is low.
- Adding a foreign key needs an index on the child columns for good delete performance on the parent. Oracle does not create that index for you.
- Adding a
NOT NULLcolumn without a default to a populated table fails with ORA-01758. Add it with aDEFAULTvalue, or add it as nullable, fill it, and then useMODIFY ... NOT NULL. - Scripts that you want to run twice should check
user_constraintsfirst. Oracle has noADD CONSTRAINT IF NOT EXISTSin these versions.
Verifying the result
After a change, confirm the new state in the data dictionary:
SELECT constraint_name, constraint_type, status, validated
FROM user_constraints
WHERE table_name = 'EMPLOYEES'
ORDER BY constraint_name;Table and constraint names are stored in uppercase unless you created them with quoted identifiers, so compare against 'EMPLOYEES'.
Exercise
The employees table has 5,000 rows. You run ALTER TABLE employees ADD CONSTRAINT employees_email_uk UNIQUE (email) and get ORA-02299. Describe how you find the cause, and what you must watch for before you later drop departments_pk with CASCADE.
Show answer
ORA-02299 means duplicate keys exist, so the constraint was not created. Run SELECT email, COUNT(*) FROM employees GROUP BY email HAVING COUNT(*) > 1 to list the duplicated values, or repeat the statement with EXCEPTIONS INTO exceptions to capture the rowids. Fix or remove the duplicate rows, then run the ALTER again. Before dropping departments_pk with CASCADE, query user_constraints for rows whose r_constraint_name is DEPARTMENTS_PK. CASCADE also drops those foreign keys, such as employees_dept_fk, and the child tables would then accept rows with no matching department.