Constraints are the rules applied on data columns on table. These are used to bound the type of data that can go into a table. This ensures the accuracy and consistency of the data. If there is any violation between the constraint and the data action, the action is aborted by the constraint
Constraints can be specified when the table is created or after the table is created.
Constraints could be column level or table level. Column level constraints are applied only to one column, whereas table level constraints are applied to the whole table.
The commonly used constraints are:
- Not NULL
- PRIMARY KEY
- FOREIGN KEY
- Not NULL:
It indicates that the column cannot have null value.
It ensures that all the values in the column are unique.
- PRIMARY KEY:
It is a key which helps you to find the data from the table. It must be unique and not null.
- FOREGIN KEY
A foreign key is a field in a relational table that matches the primary key column of another table.
It checks whether all values meets the specific condition or not.
It provides the default value when the value is not specified.
CREATE TABLE table_name
Column1 datatype (size) constraint_name,
Column2 datatype (size) constraint_name,
Column3 datatype (size) constraint_name,