Content deleted Content added
→Definition: typo |
Asilvering (talk | contribs) m Removing link(s) Wikipedia:Articles for deletion/Where (SQL) closed as delete (XFDcloser) |
||
(29 intermediate revisions by 28 users not shown) | |||
Line 1:
{{Short description|Type of integrity constraint in SQL}}
A '''check constraint'''
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:
If these constraints were not in place, it would be possible to have a negative price (
Check constraints are used to ensure the [[Data validation|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==
Line 15 ⟶ 16:
Each check constraint has to be defined in the <code>CREATE TABLE</code> or <code>ALTER TABLE</code> statement using the syntax:
...,
CONSTRAINT ''constraint_name'' CHECK ( ''predicate'' ),
...
If the check constraint refers to a single column only, it is
...
''column_name'' ''type'' CHECK ( ''predicate'' ),
...
==NOT NULL
A <code>NOT [[Null (SQL)|NULL]]</code> constraint is functionally equivalent to the following check constraint with an <code>IS NOT NULL</code> predicate:
Some [[
== Common
Most database management systems restrict check constraints to a single row
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 <code>INSERT</code> or <code>UPDATE</code> triggers, [[integrity constraints]] could be violated by indirect action were it not for these limitations. Furthermore, otherwise-valid modifications to these records would then be prevented by the <code>CHECK</code> constraint. Some examples of dangerous constraints include:
== References ==▼
<references/>▼
* {{code|2=sql|1=CHECK ((select count(*) from invoices where invoices.customerId = customerId) < 1000)}}
* {{code|2=sql|1=CHECK (dateInserted = CURRENT_DATE)}}
* {{code|2=sql|1=CHECK (countItems = RAND())}}
User-defined [[Database trigger|triggers]] can be used to work around these restrictions. Although similar in implementation, it is semantically clear that triggers will only be fired when the table is directly modified, and that it is the designer's responsibility to handle indirect, important changes in other tables; constraints on the other hand are intended to be "true at all times" regardless of the user's actions or the designer's lack of foresight.
▲== References ==
▲<references/>
[[
|