Constraints - Constraints are the rules enforced on data columns on table. This ensures the accuracy and reliability of the data in the database. Constraints define some conditions that restricts the column to remain true while inserting or updating or deleting data in column. Constraints can be defined in two ways 1) The constraints can be specified immediately after the column definition. This is called column-level definition. 2) The constraints can be specified after all the columns are defined. This is called table-level definition. Types of Constraints in SQL-Server NOT NULL - This constraint is responsible for a column to confirm that a column cannot have a null value. DEFAULT – This constraint provides a default value when specified non for this column. UNIQUE - This constraint insure that each row for the column has different value. PRIMARY KEY - Primary key constraint is a combination of a NOT NULL constraint and a UNIQUE constra
CHECK- The CHECK responsible to enables a condition to check the value being entered into a record Example- In following example we create PRODUCT table it has PRICE column and its value should be greater than 20.00, so that you cannot have any product which price is less than or equal to 20.00 CREATE TABLE PRODUCT ( ID INT NOT NULL IDENTITY ( 1 , 1 ), SKU VARCHAR ( 20 ) NOT NULL, TITLE VARCHAR ( 200 ) NOT NULL, PRICE MONEY NOT NULL CHECK ( PRICE > 20.00 ), DISCRIPTION VARCHAR ( 2000 ) NULL, DTCREATE DATETIME NULL CONSTRAINT pk_ID PRIMARY KEY ( ID ) ) If table already exists then use following query to create check constraints. ALTER TABLE PRODUCT ADD CHECK ( PRICE > 20.00 )