Funda Lecture 5
Funda Lecture 5
SQL Constraints - SQL constraints are used to specify rules for the data in a table. If there is an
between the constraint and the data action, the action is aborted by the constraint.
(***Note: Constraints can be specified when the table is created (inside the CREATE TABLE state
or after the table is created inside the ALTER TABLE statement. ***)
Sample Code:
SQL CREATE TABLE + CONSTRAINT Syntax
CREATE TABLE table_name
(
column_name1 data_type(size) constraint_name,
column_name2 data_type(size) constraint_name,
column_name3 data_type(size) constraint_name,
....
);
3. NOT NULL - Indicates that a column cannot store NULL value. The NOT NULL constraint enfor
to NOT accept NULL values.
***(Note: The NOT NULL constraint enforces a field to always contain a value. This means that y
cannot insert a new record, or update a record without adding a value to this field.***)
5. PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Ensures that a column (or combin
of two or more columns) have a unique identity which helps to find a particular record in a table
easily and quickly
(***Note: The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness
column or set of columns. A PRIMARY KEY constraint automatically has a UNIQUE constraint d
Thus, you can have many UNIQUE constraints per table, but only one PRIMARY KEY constrain
table. ***)
6. FOREIGN KEY - Ensure the referential integrity of the data in one table to match values in an
A FOREIGN KEY in one table points to a PRIMARY KEY in another table. Refer to the table below:
2 44678 3
3 22456 2
4 24562 1
(***Note: The "P_Id" column in the "Orders" table points to the "P_Id" column in the "Persons" ta
The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.
The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.
The FOREIGN KEY constraint also prevents invalid data from being inserted into the foreign key c
because it has to be one of the values contained in the table it points to.***).
Or