Constraints in SQL
Constraints in SQL
BY: SIRI
RAMIDI
CONSTRAINTS
Sql constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table.
This ensures the accuracy and reliability of the data in the table.
If there is any violation between the constraint and the data action, the
action is aborted.
Constraints can be column level or table level. Column level constraints apply
to a column, and table level constraints apply to the whole table.
The following constraints are commonly used in SQL:
NOT NULL constraint :
The NOT NULL constraint enforces a column to NOT accept NULL values.
This enforces a field to always contain a value, which means that you cannot insert a new
record, or update a record without adding a value to this field.
Example:
CREATE TABLE persons (
ID int NOT NULL,
lastname varchar(255) NOT NULL,
firstname varchar(255) NOT NULL,
age int
);
UNIQUE constraint:
The UNIQUE constraint ensures that all values in a column are different.
Both the unique and primary key constraints provide a guarantee for uniqueness for a column or set
of columns.
A primary key constraint automatically has a unique constraint.
However, you can have many unique constraints per table, but only one primary key constraint per
table.
Example: The following SQL creates a UNIQUE constraint on the "ID" column when the "Persons" table is
created:
Example: The following SQL creates a FOREIGN KEY on the "personid" column when the "orders"
table is created:
Example: The following SQL sets a DEFAULT value for the "City" column when the "Persons" table is
created: