Foreign keys v16
A foreign key represents one or more than one column used to establish and enforce a link between data in two database tables for controlling data stored in the foreign key table.
Suppose you want to make sure all employees belong to a valid department, that is, you want to maintain the referential integrity of your data. In simplistic database systems, you can ensure referential integrity by first looking at the
dept table to check if a matching record exists and then inserting or rejecting the new employee record.
This approach has a number of problems and is inconvenient. EDB Postgres Advanced Server can make it easier for you.
A modified version of the
emp table presented in Creating a new table is shown here with the addition of a foreign key constraint. The modified
emp table looks like the following:
If you try to issue the following
INSERT command in the sample
emp table, the foreign key constraint
emp_ref_dept_fk is meant to ensure that department
50 exists in the
dept table. Since it doesn't, the command is rejected.
You can finely tune the behavior of foreign keys to your application. Making correct use of foreign keys improves the quality of your database applications. We strongly encourage you to learn more about them.