Designing check constraints
When creating check constraints, one of two things can happen: (i) all the rows meet the check constraint, or (ii) some or all the rows do not meet the check constraint.
About this task
- All the rows meet the check constraint
- When all the rows meet the check constraint, the check constraint will be created successfully. Future attempts to insert or update data that does not meet the constraint business rule will be rejected.
- Some or all the rows do not meet the check constraint
- When there are some rows that do not meet the check constraint,
the check constraint will not be created (that is, the ALTER TABLE
statement will fail). The ALTER TABLE statement, which adds a new
constraint to the EMPLOYEE table, is shown in the following example.
The check constraint is named CHECK_JOB. The database manager will
use this name to inform you about which constraint was violated if
an INSERT or UPDATE statement fails. The CHECK clause is used to define
a table-check constraint.
An ALTER TABLE statement was used because the table had already been defined. If there are values in the EMPLOYEE table that conflict with the constraint being defined, the ALTER STATEMENT will not be completed successfully.ALTER TABLE EMPLOYEE ADD CONSTRAINT check_job CHECK (JOB IN ('Engineer', 'Sales', 'Manager'));
As check constraints and other types of constraints are used to implement business rules, you might need to change them from time to time. This could happen when the business rules change in your organization. Whenever a check constraint needs to be changed, you must drop it and re-create a new one. Check constraints can be dropped at any time, and this action will not affect your table or the data within it. When you drop a check constraint, you must be aware that data validation performed by the constraint will no longer be in effect.