DDL Foreign key


Foreign key is the key which is reference from another table. In other words, Foreign Key is a Primary key on other table (Parent table) and that can be referred in current table(child table) with other column name or same column name.

Foreign key can be defined in either CREATE TABLE or ALTER TABLE. Foreign key definition is optional in CREATE TABLE or ALTER TABLE.

Foreign key can have a NULL values in the table (Child table) where it is declared as Foreign key. Foreign key will create the referential constraint between the Parent table and Child table.

Syntax -


FOREIGN KEY(Column1, Column2..) REFERNCES Source-table 
CASCADE/RESTRICT/SET NULL

CASCADE - When the row deleted in parent table, the corresponding rows in child table will get deleted.

RESTRICT - If any row in the parent table has the references in the child table. The row in the parent table will not get deleted even though the delete operation performed on it.

SET NULL -When the row deleted in parent table, the corresponding rows in the child table will be set with NULL.