23 April 2014

ChecK Constraint

The CHECK Constraint enables a condition to check the value being entered into a record. If the condition evaluates to false, the record violates the constraint and isn't entered into the table.

Example:

For example, the following SQL creates a new table called CUSTOMERS and adds five columns. Here, we add a CHECK with AGE column, so that you can not have any CUSTOMER below 18 years:
Create table Customers
(
Id      int  not null,
name Varchar(20) not null,
Age int not check(Age>=18) 
Address char(25),
Salary Decimal(18,2),
Primary key(id)
);  
If CUSTOMERS table has already been created, then to add a CHECK constraint to AGE column, you would write a statement similar to the following:

Alter table customers modify age int not null check(Age>=18);
You can also use following syntax, which supports naming the constraint in multiple columns as well:

Alter table customers add constraint mycheckconstraint check(Age>=18);

DROP a CHECK Constraint:

To drop a CHECK constraint, use the following SQL. This syntax does not work with MySQL:

Alter table Customers drop constraint myCheckConstraint;

No comments:

Post a Comment