SQL constraints are conditions / rules that apply on the data columns of a table which is used to limit the type of data that goes inside the table.
Constraints are used to specify the rules
concerning data in the table. It can be applied for single or multiple fields
in an SQL table during the creation of the table or after creating using the
ALTER TABLE command.
There
are 3 types of Constraints:
A) Key Constraint
B) Domain Constraint
C) Referential Integrity Constraint
The PRIMARY KEY constraint uniquely identifies each row in a table. It must contain UNIQUE values and has an implicit NOT NULL constraint.
A table in SQL is strictly restricted to have one and only one primary key, which is comprised of single or multiple fields (columns).
A UNIQUE constraint ensures that all values in a column are different. This provides uniqueness for the column(s) and helps identify each row uniquely. Unlike primary key, there can be multiple unique constraints defined per table. The code syntax for UNIQUE is quite similar to that of PRIMARY KEY and can be used interchangeably.
A FOREIGN KEY
comprises of single or collection of fields in a table that essentially refers
to the PRIMARY KEY in another table. Foreign key constraint ensures referential
integrity in the relation between two tables.
The table with the foreign key constraint is labelled
as the child table, and the table containing the candidate key is labelled as
the referenced or parent table.
