Skip to main content

Foreign Key Configuration

Foreign keys are important constraints in PostgreSQL databases used to establish and maintain relationships between two tables. Foreign key constraints ensure referential integrity, preventing invalid data from being inserted or updated.

Configure Foreign Keys

You can configure foreign key constraints in the console or with SQL statements. The console is suitable for common table and column configuration, while SQL is better for bulk changes, migration scripts, and more advanced constraint configuration.

  1. Go to the CloudBase Console / PostgreSQL Database / Tables management page.
  2. Select the target environment and table.
  3. Click New Column, or edit an existing column.
  4. Check Set as Foreign Key in the column configuration.
  5. Select the referenced table and referenced column, then configure the delete rule, update rule, and other parameters.
  6. Confirm the configuration and submit it. Wait until the foreign key constraint is created.

The referenced column usually needs to be the primary key or a unique column of the parent table. If the delete rule is Set Null, the foreign key column in the child table must allow NULL.

Foreign Key Parameters

ParameterDescriptionRequiredExample
Foreign Key NameName of the foreign key constraintYesfk_user_department
Referenced TableName of the parent table referenced by the foreign keyYesdepartments
Referenced ColumnName of the referenced column in the parent tableYesid
Delete RuleAction taken when a parent record is deletedYesCascade
Update RuleAction taken when the referenced field in the parent table is updatedYesNo Action

Delete and Update Rules

RuleIdentifierDescription
No ActionNO ACTIONRejects the operation if referenced records exist in the child table
RestrictRESTRICTSimilar to NO ACTION, immediately checks and rejects the operation
CascadeCASCADEAutomatically propagates the operation to all referencing records in the child table
Set NullSET NULLSets the foreign key field in the child table to NULL
Set DefaultSET DEFAULTSets the foreign key field in the child table to its default value
tip

For more details and advanced usage of foreign key constraints, refer to the PostgreSQL Official Documentation - Foreign Keys.