In this blog, I’m explaining about constraints in SQL.

Description:

 SQL constraints are used to restrict the type of data that can insert into a database table. Constraints can be defined in two ways.

Column Level    : limits on column data

Table Level        : Limits on table data

 

Types of SQL constraints 


·         Not null


·         Unique key


·         Primary key


·         Foreign key


·         Check


·         Default 


Not Null Constraints


This  constraint ensures that  all rows  in the database table must contain


value for the  column which specified as not null  means  a null value is not


allowed in the column.


Syntax:



Create table table_name
( col1 datatype[CONSTRAINT cons_name] not null,
Col2 datatype,
)

 

Unique key Constraints

Unique key  is a set  of one or more columns of a table that uniquely


identify each record in database table. It is like a Primary key but it can


accept only one null value and it can not have duplicate values.


Syntax:
Create table table_name
( col1 datatype[CONSTRAINT cons_name] unique,
Col2 datatype,
)

 

Primary key Constraints

Primary key is a set  of  one  or more  columns of a table that  uniquely


identify each in database table. It can not  accept null, duplicate  values.



Syntax:
Create table table_name
( col1 datatype[CONSTRAINT cons_name] PRIMARY KEY,
Col2 datatype,
)
 

 

 Foreign Key Constraints


Foreign key is a field in database table that is Primary key in another table.


It  can accept multiple null ,duplicate values.


Syntax:


Create table table_name
( col1 datatype[CONSTRAINT cons_name] references
 reference_table_name (reference_table_column_name),
col2 datatype
)

 

Check Constraints

This constraint defines a business rules on a column in the  database table


that each row of the table must  follow this rule.



Syntax:
Create table table_name
(
 Col1 datatype[CONSTRAINT cons_name] check(condition)
Col2 datatype
)

 

Default constraints

The Default constraint is used to insert a default value into a column.


The default value will be added  to all new records, if  no  other value is


specified.

 

Syntax:
Create table table_name
( Col1 datatype,
Col2  datatype Default Getdate()
)

Leave Comment