Constraints in SQL

• Constraint is a rule which is applied on a column.
• Constraint is used to maintain accurate and quality data.
• Constraint restricts the user from entering invalid data.
• The goal of constraint is maintaining accurate and quality data. This
feature is called “Data Integrity”.
• SQL provides Data Integrity.

SQL provides following constraints to maintain the Data Integrity:
1. Primary Key
2. Unique
3. Not Null
4. Check
5. Default
6. References [Foreign Key]

1. Primary Key:

• It should not accept duplicate values.
• It should not accept null values.
• If our requirement is not to accept duplicate value and null value in
a column then use it.

2. Unique:

• It should not accept duplicate values.
• It accepts null values.
• If our requirement is accepting null values but not accepting
duplicate values, then use it.

3. Not Null:

• It should not accept null values.
• It can accept duplicate values.
• When we want to accept duplicate value and demand for entering
a value in field then use it.

4. Check:

It is used to write our own conditions [rules] on a column.
Example:
If M1 value Must be between 0 to 100 only then write:
M1 Number(3) Check(M1>=0 and M1<=100)
If Gender value must be M or F only then write:
Gender Char(1) Check(Gender=‘M’ or ‘F’)
If salary must be between 5000 to 100000 then write:
Salary Number(8,2) Check(Salary>=5000 and Salary<=100000)

5. Default:

• It is used to apply default value to a column.
• We have no need to pass this value when we insert the record. It
will be taken automatically when we don’t pass the value.
• If we pass the value, it takes the value. If we don’t pass the value,
it takes default value.

6. References [Foreign Key]:

Foreign Key refers to primary key values of another table.