Categories
Sql Server

How to create CHECK Constraint in Sql server

CHECK Constraint in Sql server

CHECK constraint is to limit the value range that can be inserted in a column.

If you define a CHECK constraint on a single column it allows only certain values for this column that you are defined with in check constraint.

Query To create CHECK constraint:-


CREATE TABLE hightech ( Id int NOT NULL CHECK (Id>0),
Name varchar(255) NOT NULL, Address varchar(255), City varchar(255) )

Second way to create a check constraint:-


CREATE TABLE hightech2 ( Id int NOT NULL, Name varchar(255) NOT NULL,
City varchar(255),CONSTRAINT CHK_CONS CHECK (Id>0 AND City='Delhi') )


How to create a check constraint in already created table.


ALTER TABLE hightech ADD CONSTRAINT chk_const CHECK Id>0 AND City='delhi'


How to drop check constraint:-


ALTER TABLE hightech DROP CONSTRAINT chk_cons