For example, in a table containing products, one could add a check constraint such that the price of a product and quantity of a product is a non-negative value:
PRICE >= 0
QUANTITY >= 0If these constraints were not in place, it would be possible to have a negative price (-$30) or quantity (-3 items).
Check constraints are used to ensure the validity of data in a database and to provide data integrity. If they are used at the database level, applications that use the database will not be able to add invalid data or modify valid data so the data becomes invalid, even if the application itself accepts invalid data.
Definition
Each check constraint has to be defined in theCREATE TABLE
or ALTER TABLE
statement using the syntax:CREATE TABLE table_name ( ..., CONSTRAINT constraint_name CHECK ( predicate ), ... )
ALTER TABLE table_name ADD CONSTRAINT constraint_name CHECK ( predicate )If the check constraint refers to a single column only, it is possible to specify the constraint as part of the column definition.
CREATE TABLE table_name ( ... column_name type CHECK ( predicate ), ... )
NOT NULL Constraint
A NOT NULL constraint is functionally equivalent to the following check constraint with anIS NOT NULL
predicate:CHECK (column IS NOT NULL)Some relational database management systems are able to optimize performance when the
NOT NULL
constraint syntax is used as opposed to the CHECK constraint syntax given above.Common Restrictions
Most database management systems restrict check constraints to a single row, with access to constants and deterministic functions, but not to data in other tables, or to data invisible to the current transaction because of transaction isolation.Such constraints are not truly table check constraints but rather row check constraints. Because these constraints are generally only verified when a row is directly updated (for performance reasons,) and often implemented as implied INSERT or UPDATE triggers, integrity constraints could be violated by indirect action were it not for these limitations. Future, otherwise-valid modifications to these records would then be prevented by the CHECK constraint. Some examples of dangerous constraints include:
- CHECK ((select count(*) from invoices where invoices.customerId = customerId) < 1000)
- CHECK (dateInserted = CURRENT_DATE)
- CHECK (countItems = RAND())
from : wikipedia.org
0 comments:
Post a Comment