SQL Constraints
SQL Constraints
- SQL constraints are used to specify rules for the data in a table.
- A constraint is something that limits 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:
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:
Example:
- Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for
uniqueness for a column or set of columns.
3. PRIMARY KEY
- A Primary key uniquely identifies each row table.
- It must contain not null and unique values.
- A table can have only one primary key, which may consist of single or multiple
fields.
- When multiple fields are used as a primary key, they are called composite keys.
- To create a Primary key in the table, we have to use a keyword; “PRIMARY KEY ( )
- Syntax:
- CREATE TABLE table_name
(
column1 datatype null/not null,
column2 datatype null/not null,
...
CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ... column_n) );
- Example:
4. FOREIGN KEY.
- Foreign key is used to create a link between two tables.
-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.