SQL Constraints

SQL Constraints

SQL constraints are used to specify data rules in a table.

If there is a data behavior that violates the constraint, the behavior will be terminated by the constraint.

Constraints can be specified when the table is created (via the CREATE TABLE statement) or after the table is created (via the ALTER TABLE statement).


CREATE TABLE table_name
column_name1 data_type(size) constraint_name,
column_name2 data_type(size) constraint_name,
column_name3 data_type(size) constraint_name,

In SQL, we have the following constraints:

  • NOT NULL -indicates that a column cannot store NULL values.
  • UNIQUE -Ensure that each row of a column has a unique value.
  • PRIMARY KEY -A combination of NOT NULL and UNIQUE. Ensuring that a column (or a combination of two columns and multiple columns) is uniquely identified can help make it easier and faster to find a particular record in a table.
  • FOREIGN KEY -Guarantees the referential integrity of the data in one table to the values in another table.
  • CHECK -The values in the column are guaranteed to meet the specified criteria.
  • DEFAULT -Specifies the default value when no value is assigned to the column.

In the following sections, we will explain each constraint in detail.