Foreign Key
FOREIGN KEY is used to form a relationship between two tables and to prevent actions that would destroy links between the linked tables. One or multiple fields can be made as a foreign key. Foreign key should always refer to the primary key in another table.
Example Usage
In this example we've created an table called users that holds all the users. We also have a table called cars and each of the car belongs to one user. So we have created a foreign key for column ownerId in the cars table to reference to userId in the users table:
CREATE TABLE users (
userId INT NOT NULL AUTO_INCREMENT,
name CHAR(250) NOT NULL,
PRIMARY KEY (userId));
CREATE TABLE cars (
carId INT NOT NULL AUTO_INCREMENT,
platenumber VARCHAR(50) NOT NULL,
ownerId INT NOT NULL,
FOREIGN KEY (ownerId) REFERENCES users(userId),
PRIMARY KEY(carId));
Testing the Behavior
Insert couple users to the table:
Verify that the users exist:
Example Output
Then, insert couple cars:
And verify that the cars exist:
Example Output
And as a last thing, try removing from user, which still has car assigned to him / her:
The last query should give you an error because you cannot remove user with an ID of 1 because that user still has cars in the cars table.