Why do we use SQL constraints? Which constraints we can use while creating a table in SQL?

Why do we use SQL constraints? Which constraints we can use while creating a database in SQL?

Last updated:9/22/2021 2:15:10 AM

1 Answers

Ashutosh Kumar Verma
Ashutosh Kumar Verma

SQL Constraints ;

  SQL Constraints is a set of rules that specifies for the data in database table. Constraints are specified when a table is created or after table is created with SQL ALTER command.


    CREATE TABLE table_name(

    column1 datatype constraint,
    column2 datatype constraint,

Use of SQL Constraints:

    SQL Constraints is used to provide a set of rules to columns in database tables. SQL Constraints can provide in table during creation of table or alter of tables.

SQL Constraints can either column level or table level. The column level constraints are apply on single column and table level column are applied on whole tables. 

There are several types of SQL Constraints are used when a table is create, which are as follow-

1-  NOT NULL Constraints-     This constraint is used when no column is to be kept empty. NOT NULL constraints prevent the value of a column from being null. When this constraint is used in a column, then null value cannot be provided to that column.

2-  Primary key constraints-     These constraints uniquely identify each row (record) in the database table. A primary key can never contain a null value. It always contains a unique value.

3-  Foreign key constraints-     Foreign key constraints are used to provide a link between the data in two tables. This constraint is used to enforce referential integrity.

4-   Check constraints-     Check constraints are used to limit the value set in the column. It checks all the value of column based on condition.

5-   UNIQUE Constraints-     Unique constraints shows the uniqueness of the value of the column. Unique constraints ensure that the column or field contains only unique values, which means that all the values of the column will be different.

6-  DEFAULT Constraints-     This constraint is used to provide default value to the column. When no value is provided to a column, then Default Constraints are used.

7-   INDEX-     Index is used to quickly retrieve or create data in any database table.