SQL constraints
SQL Constraints
SQL constraints are used to specify the data rules in the table.
If there is data behavior that violates constraints, the behavior will be terminated by the constraints.
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).
SQL CREATE TABLE + CONSTRAINT Syntax
(
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 - Guarantees that each row of a column must have a unique value.
PRIMARY KEY - Combination of NOT NULL and UNIQUE. Ensuring that a column (or a combination of two or more columns) has a unique identifier can help make it easier and faster to find a specific record in a table.
FOREIGN KEY - Ensures referential integrity that data in one table matches values in another table.
#CHECK - Ensures that the values in the column meet the specified conditions.
DEFAULT - Specifies the default value when no value is assigned to the column.
In the following chapters, we will explain each constraint in detail.