23.10.2012 Views

Structured Query Language (SQL) - Cultural View of Technology

Structured Query Language (SQL) - Cultural View of Technology

Structured Query Language (SQL) - Cultural View of Technology

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Check Constraint 19<br />

Check Constraint<br />

A check constraint (also known as table check constraint) is a condition that defines valid data when adding or<br />

updating an entry in a table <strong>of</strong> a relational database. A check constraint is applied to each row in the table. The<br />

constraint must be a predicate. It can refer to a single or multiple columns <strong>of</strong> the table. The result <strong>of</strong> the predicate can<br />

be either TRUE, FALSE, or UNKNOWN, depending on the presence <strong>of</strong> NULLs. If the predicate evaluates to<br />

UNKNOWN, then the constraint is not violated and the row can be inserted or updated in the table. This is contrary<br />

to predicates in WHERE clauses in SELECT or UPDATE statements.<br />

For example, in a table containing products, one could add a check constraint such that the price <strong>of</strong> a product and<br />

quantity <strong>of</strong> a product is a non-negative value:<br />

PRICE >= 0<br />

QUANTITY >= 0<br />

If these constraints were not in place, it would be possible to have a negative price (-$30) or quantity (-3 items).<br />

Check constraints are used to ensure the validity <strong>of</strong> data in a database and to provide data integrity. If they are used<br />

at the database level, applications that use the database will not be able to add invalid data or modify valid data so<br />

the data becomes invalid, even if the application itself accepts invalid data.<br />

Definition<br />

Each check constraint has to be defined in the CREATE TABLE or ALTER TABLE statement using the syntax:<br />

CREATE TABLE table_name (<br />

)<br />

...,<br />

CONSTRAINT constraint_name CHECK ( predicate ),<br />

...<br />

ALTER TABLE table_name<br />

ADD CONSTRAINT constraint_name CHECK ( predicate )<br />

If the check constraint refers to a single column only, it is possible to specify the constraint as part <strong>of</strong> the column<br />

definition.<br />

CREATE TABLE table_name (<br />

)<br />

...<br />

column_name type CHECK ( predicate ),<br />

...

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!