Monday, May 11, 2009

Constraints in SQL

A constraint in SQL Server is a way to enforce rules on what kind of data can be added or how data can be modified in SQL Tables. These are basically used to avoid any kind of inconsistencies in the database and can be described as assigning properties to the columns. These constraints are categorized into four main categories :

1. Entity Constraints : It ensures that duplicate data is not inserted into the table. This is done by adding Primary Key constraint which ensures that a column can not have a duplicate value. For ex : To make sure that no value of a column named EmpId in a column is repeated , Primary Key constraint is added.

2. Domain Constraints : These constraints are added to ensure that data being added is within the range and type of the datatype of the column. For example to make sure that no value in a column named EmpID is > 50 , this constraint is used. This type of constraint is implemented using the Check constraint which makes sure that no value greater than 50 is added in the EmpID column.

3. Refrential Integrity Constraint : This type of constraint is added to make sure that data from a table is not deleted if any of its columns is having relation with another table in the database i.e. any other table is dependent on the parent table. This type of constraint isimplemented by the concept of Foreign Key Constraint. For ex : if a table named tbEmp is having EmpID as Primary Key and is referring to EmpID column (which acts as Foreign Key) of another table named tbDepartment , the Foreign Key Constraint makes sure that no data from parent table tbEmp is deleted until all the underlying values from tbDepartment are deleted.

4. User Defined Constraints : These are some rules defined by users which are not in the above

No comments:

Post a Comment