;

SQL CONSTRAINTS


In this tutorial, we will learn what is CONSTRAINT and how to use SQL.

SQL CONSTRAINTS

  • SQL CONSTRAINT is assigned to a column or a set of columns of the table that prevents the column from certain types of inconsistent values insertions in those columns.
  • SQL CONSTRAINT ensures the column to follow the specified rules. i.e. NOT NULL constraint ensures that column cannot have NULL values.
  • SQL CONSTRAINT can be assigned when the table is created OR after the table is created using an ALTER TABLE statement.
  • SQL CONSTRAINT is used to enforce data integrity. This ensures the accuracy and reliability of the data in the table.

Adding constraints with the CREATE TABLE statement

Syntax - Adding constraints with the CREATE TABLE statement
CREATE TABLE table_name (
    column1 datatype constraint,
    column2 datatype constraint,
    column3 datatype constraint,
    ....
    columnN datatype constraint,
); 

The most commonly used SQL Constraint are as follow:

  • NOT NULL: It ensures that the column can not have a NULL value.
  • UNIQUE: It ensures that all the values in a column are different or unique. A table can have multiple unique constraints.
  • PRIMARY KEY: It is a combination of a NOT NULL and UNIQUE constraint. PRIMARY KEY constraint is used to uniquely identify each row and only one primary key constraint can be created for each table.
  • FOREIGN KEY: It prevents any actions that would destroy a link between tables with the corresponding data values. A FOREIGN KEY in one table points to a primary key in another table.
  • CHECK: It ensures that all values in a column satisfy a specific condition.
  • DEFAULT: It is used to set a default value for a column when NULL or no value is specified to a column.
  • INDEX: It is used to create and retrieve data from the database very quickly.