In Oracle, you can add a CHECK constraint to an existing table using the ALTER TABLE statement. Here's the syntax:
Example:
Suppose you have a table employees and you want to add a CHECK constraint to ensure that the salary column is greater than 3000.
Adding a CHECK Constraint on Multiple Columns:
You can also apply a CHECK constraint involving multiple columns. For example:
Notes:
The
CHECKconstraint ensures that all new or updated rows satisfy the condition.If existing rows violate the condition, adding the constraint will fail unless
NOVALIDATEis used.You can drop a
CHECKconstraint using:
In Oracle, a CHECK constraint cannot directly use the NOT IN clause because it does not support subqueries or set-based expressions. However, you can achieve similar functionality using AND and != conditions.
Example:
Suppose you have an employees table and want to ensure that the job_title column does not contain certain values like 'Intern' and 'Trainee'. You can define the CHECK constraint like this:
Alternative Approach:
If you need more complex conditions (e.g., checking values dynamically from another table), consider using:
- Triggers – For enforcing complex constraints.
- Foreign Key with
ON DELETErules – If restricting values based on another table.