alter table add column foreign key code example
Example 1: mysql add foreign key
CREATE TABLE tableName (
ID INT,
SomeEntityID INT,
PRIMARY KEY (ID),
FOREIGN KEY (SomeEntityID)
REFERENCES SomeEntityTable(ID)
ON DELETE CASCADE
);
ALTER TABLE
tableName
ADD
FOREIGN KEY (SomeEntityID) REFERENCES SomeEntityTable(ID) ON DELETE CASCADE;
ALTER TABLE
tableName
ADD CONSTRAINT fk_name
FOREIGN KEY (SomeEntityID) REFERENCES SomeEntityTable(ID) ON DELETE CASCADE;
Example 2: foreign key in sql
A FOREIGN KEY is a key used to link two tables together.
A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in another table.
The table containing the foreign key is called the child table, and the table containing the candidate key is called the referenced or parent table.
Example:
CREATE TABLE users(
user_id INT NOT NULL,
user_name VARCHAR(64) NOT NULL,
user_pass VARCHAR(32) NOT NULL,
PRIMARY KEY(user_id);
);
INSERT INTO users VALUES(1,"Raj","raj@123");
CREATE TABLE orders(
order_id INT NOT NULL,
order_description VARCHAR(255),
orderer_id INT NOT NULL,
PRIMARY KEY(order_id),
FOREIGN KEY (orderer_id) REFERENCES users(user_id)
);
INSERT INTO orders VALUES(1,"Daily groceries",1);
Example 3: add new column in sql with foreign key
ALTER TABLE `fb_banners`
ADD `city_id` BIGINT(20) UNSIGNED NULL DEFAULT NULL AFTER `BannerID`,
ADD INDEX `Foreign_city_id_banners` (`city_id`) USING BTREE,
ADD CONSTRAINT `Foreign_city_id_banners` FOREIGN KEY (`city_id`) REFERENCES `foodsafari`.`fb_cities` (`id`) ON UPDATE CASCADE ON DELETE CASCADE;