The foreign key places constraints on data in the related tables, which allows MySQL to maintain referential integrity. There are three types of relationships that can exist between two tables:
In the orders table has a customerNumber that exists in the customers table. Multiple rows in the orders table can have the same customerNumber.
Syntax:
CREATE TABLE categories( categoryId INT AUTO_INCREMENT PRIMARY KEY, categoryName VARCHAR(100) NOT NULL ) ENGINE=INNODB;
CREATE TABLE products( productId INT AUTO_INCREMENT PRIMARY KEY, productName varchar(100) not null, categoryId INT, CONSTRAINT fk_category FOREIGN KEY (categoryId) REFERENCES categories(categoryId) ) ENGINE=INNODB;
The categoryId in the products table is the foreign key column that refers to the categoryId column in the categories table.
Because we don’t specify any ON UPDATE and ON DELETE clauses, the default action is RESTRICT for both update and delete operation.
INSERT INTO categories(categoryName) VALUES ('Smartphone'), ('Smartwatch');
INSERT INTO products(productName, categoryId) VALUES('iPhone',1); INSERT INTO products(productName, categoryId) VALUES('iPad',3); //error UPDATE categories SET categoryId = 100 WHERE categoryId = 1; //error
CREATE TABLE products( productId INT AUTO_INCREMENT PRIMARY KEY, productName varchar(100) not null, categoryId INT NOT NULL, CONSTRAINT fk_category FOREIGN KEY (categoryId) REFERENCES categories(categoryId) ON UPDATE CASCADE ON DELETE CASCADE ) ENGINE=INNODB;
INSERT INTO products(productName, categoryId) VALUES ('iPhone', 1), ('Galaxy Note',1), ('Apple Watch',2), ('Samsung Galary Watch',2);
DELETE FROM categories WHERE categoryId = 2;
CREATE TABLE categories( categoryId INT AUTO_INCREMENT PRIMARY KEY, categoryName VARCHAR(100) NOT NULL )ENGINE=INNODB; CREATE TABLE products( productId INT AUTO_INCREMENT PRIMARY KEY, productName varchar(100) not null, categoryId INT, CONSTRAINT fk_category FOREIGN KEY (categoryId) REFERENCES categories(categoryId) ON UPDATE SET NULL ON DELETE SET NULL )ENGINE=INNODB; INSERT INTO categories(categoryName) VALUES ('Smartphone'), ('Smartwatch'); INSERT INTO products(productName, categoryId) VALUES ('iPhone', 1), ('Galaxy Note',1), ('Apple Watch',2), ('Samsung Galary Watch',2); UPDATE categories SET categoryId = 100 WHERE categoryId = 1; DELETE FROM categories WHERE categoryId = 2;