how to make primary key and foreign key in sql 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: what is foreign key
Foreign Key:
It is a column that comes from a different table and
using Foreign key tables are related each other
It is the primary key of another table
It can be duplicate or null for another table