are foreign keys required field sql code example
Example 1: 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 2: alter table add column forigen key mysql
ALTER TABLE tryholpz_demo07.core_modules
ADD COLUMN belongs_to_role INT,
ADD FOREIGN KEY core_modules(belongs_to_role) REFERENCES role_specific_modules_info(id) ON DELETE CASCADE