FOREIGN KEY is used to limit references. When all values in one field of a table are presented in a field of another table, it is said that the first field refers to the second. This indicates a direct relationship between the values of the two fields.
When one field in a table refers to another, it is called a foreign key, and the field to which it refers is called the parent key. The names of the foreign key and the parent key do not have to be the same. A foreign key can have any number of fields, all of which are processed as a single module. The foreign key and the parent key to which it refers must have the same field number and type, and be in the same order. When a field is a foreign key, it is definitely associated with the table to which it refers. Each value, (each line) of a foreign key must explicitly refer to one and only this value (line) of the parent key. If this condition is met, the database is in a state of referential integrity.
SQL supports referential integrity with a FOREIGN KEY constraint . This function should limit the values that can be entered into the database to force the foreign key and the parent key to comply with the principle of referential integrity. One of the actions of the FOREIGN KEY constraint is to drop values for fields that are restricted as a foreign key that is not already present in the parent key. This restriction also affects the ability to change or delete parent key values.
The FOREIGN KEY constraint is used in the CREATE TABLE command (or ALTER TABLE (intended to modify the table structure) containing a field that is declared a foreign key. The parent key is given a name referenced within the FOREIGN KEY constraint .
Like most restrictions, it can be a table or column constraint, in the form of a table allowing multiple fields to be used as one foreign key.
Example: there are two users and emails tables:
CREATE TABLE users ( user_id int(11) NOT NULL AUTO_INCREMENT, user_name varchar(50) DEFAULT NULL, PRIMARY KEY (user_id) ) CREATE TABLE sys.emails ( email_id int(11) NOT NULL AUTO_INCREMENT, email_address varchar(100) NOT NULL, user_id int(11) NOT NULL, PRIMARY KEY (email_id) )
There is a dependency between them in the form of users.user_id and emails.user_id, and we want that in the emails.user_id field nothing could be written except the value from the users table in the user_id column, for this we create a restriction in the form of a foreign key:
ALTER TABLE emails ADD FOREIGN KEY (user_id) REFERENCES users (user_id) ON DELETE CASCADE ON UPDATE NO ACTION;
Suppose if we delete a user then automatically delete all the records associated with him, in this case his email address.
on delete cascade, etc. - Viktorov