SQL training part 4
SQL training part 4
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.
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
);
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.
MySQL:
MySQL:
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).
MySQL:
Note: In the example above there is only ONE PRIMARY KEY (PK_Person).
However, the VALUE of the primary key is made up of TWO COLUMNS (ID
+ LastName).
Note: If you use ALTER TABLE to add a primary key, the primary key
column(s) must have been declared to not contain NULL values (when the
table was first created).
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.
The "PersonID" column in the "Persons" table is the PRIMARY KEY in the
"Persons" table.
The FOREIGN KEY constraint prevents invalid data from being inserted
into the foreign key column, because it has to be one of the values
contained in the parent table.
MySQL:
MySQL:
ALTER TABLE Orders
DROP FOREIGN KEY FK_PersonOrder;
MySQL:
MySQL:
The default value will be added to all new records, if no other value is
specified.
MySQL:
SQL Server:
MS Access:
Oracle:
MySQL:
ALTER TABLE Persons
ALTER City DROP DEFAULT;