Constraints
Constraints
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
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 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:
Age int
);
Example:
FirstName varchar(255),
Age int
);
Primary keys must contain UNIQUE values, and cannot contain NULL values.
A table can have only ONE primary key; and in the table, this primary key
can consist of single or multiple columns (fields).
Example:
FirstName varchar(255),
Age int
);
SQL FOREIGN KEY Constraint
The FOREIGN KEY constraint is used to prevent actions that would destroy
links between tables.
A FOREIGN KEY is a field (or collection of fields) in one table, that refers to
the PRIMARY KEY in another table.
The table with the foreign key is called the child table, and the table with the
primary key is called the referenced or parent table.
Example:
PersonID int,
);
If you define a CHECK constraint on a column it will allow only certain values
for this column.
If you define a CHECK constraint on a table it can limit the values in certain
columns based on values in other columns in the row.
Example:
Age int,
CHECK (Age>=18)
);
The default value will be added to all new records, if no other value is
specified.
Example:
FirstName varchar(255),
Age int,
);