PostgreSQL Foreign Key
In this tutorial, you will learn about PostgreSQL foreign key and how to add foreign keys to tables using foreign key constraints.
The following illustrates a foreign key constraint syntax:
[CONSTRAINT fk_name]
FOREIGN KEY(fk_columns)
REFERENCES parent_table(parent_key_columns)
[ON DELETE delete_action]
[ON UPDATE update_action]
In this syntax:
First, specify the name for the foreign key constraint after the CONSTRAINT keyword. The CONSTRAINT clause is optional. If you omit it, PostgreSQL will assign an auto-generated name.
Second, specify one or more foreign key columns in parentheses after the FOREIGN KEY keywords.
Third, specify the parent table and parent key columns referenced by the foreign key columns in the REFERENCES clause.
Finally, specify the desired delete and update actions in the ON DELETE and ON UPDATE clauses.
Since the primary key is rarely updated, the ON UPDATE action is infrequently used in practice. We’ll focus on the ON DELETE action.
PostgreSQL supports the following actions:
SET NULL
SET DEFAULT
RESTRICT
NO ACTION
CASCADE