How to Add Foreign Key in SQL?

Use `ALTER TABLE` to modify the child table

Add the foreign key with `ADD CONSTRAINT`

Reference the parent table and parent column with `FOREIGN KEY` and `REFERENCES`

Ensure the child column and parent column have compatible data types

Ensure the referenced parent column is a primary key or unique key

Example: `ALTER TABLE child_table ADD CONSTRAINT fk_name FOREIGN KEY (child_column) REFERENCES parent_table(parent_column);`

To create a foreign key when creating a table, use `FOREIGN KEY (child_column) REFERENCES parent_table(parent_column)`

Example: `CREATE TABLE child_table (child_column INT, FOREIGN KEY (child_column) REFERENCES parent_table(parent_column));`

Optionally add `ON DELETE` and `ON UPDATE` actions such as `CASCADE`, `SET NULL`, or `RESTRICT`

Suggested for You

Trending Today