Foreign Keys

tags: #sql/constraints

Specifying foreign key constraint

A foreign key is a column or a set of columns in a table that refers to the primary key of another table.

It is used to establish a relationship between two tables and enforce referential integrity between them (i.e., the values in the foreign key column(s) must match the values in the primary key column(s) of the referenced table or be NULL).

To establish foreign keys, we can use the FOREIGN KEY clause:

CREATE TABLE table_name (
	column1 datatype constraint(s),
	fk_column datatype constraint(s),
	...
	FOREIGN KEY (fk_column) REFERENCES referenced_table(pk_column)
)

Adding foreign key constraint

To add a FK to an existing table, we can use the ALTER TABLE statement:

ALTER TABLE referencing_table
ADD FOREIGN KEY (fk_column) REFERENCES referenced_table(pk_column);

Adding referential triggered action clause

What is a referential triggered action?

A referential triggered action clause specifies what action should be taken on related rows in a table when a corresponding row in another table is updated or deleted. There are two types of referential triggered actions:

  1. ON UPDATE
  2. ON DELETE

General syntax for using a referential triggered action clause in MySQL:

CREATE TABLE table_name (
    column1 datatype contraint(s),
    column2 datatype constraint(s),
    ...
    FOREIGN KEY (column_name)
    REFERENCES referenced_table (column_name)
    ON UPDATE <action>
    ON DELETE <action>
);

The <action> parameter specifies the action to be taken on the related rows in the parent table when a corresponding row in the child table is updated or deleted.

What type of actions can be done?

Warning

in order for this to work, the column in the referencing table must have a default value defined.

Powered by Forestry.md