Skip to content
IT glossary
DatabasesUpdated December 3, 2026

Foreign key

Внешний ключ

A database rule that checks whether a row’s reference points to an existing row. For example, it prevents an order from using a customer ID that isn’t in the customers table.

Why foreign keys exist

An order can store a customer’s ID rather than repeating the customer’s name and address. But calling a column customer_id does not tell the database to check that the customer exists. A foreign key makes that check part of the schema, so it applies no matter which app, script, or import writes the data. Keeping references valid this way is called referential integrity.

What the database checks

A foreign key can cover one column or several. It normally points to a primary key or to a set of columns declared UNIQUE. It can even point back to the same table: employees.manager_id can reference employees.id. The values on the referencing side can repeat, which is how several orders can point to one customer. For a single-column foreign key, NULL means there is no reference to check. Add NOT NULL if every row must have a reference.

Example: keeping orders and customers consistent

CREATE TABLE customers (
    id bigint PRIMARY KEY
);

CREATE TABLE orders (
    id bigint PRIMARY KEY,
    customer_id bigint NOT NULL
        REFERENCES customers (id) ON DELETE NO ACTION
);

An order for customer 42 can be inserted only if that customer exists. With the rule shown above, trying to delete customer 42 while orders still point to that row fails. Choose a different rule if the data should behave differently: ON DELETE CASCADE deletes the related rows, while ON DELETE SET NULL keeps them but clears the reference. SET NULL would require dropping NOT NULL in this example. There is a separate ON UPDATE rule for changes to the referenced key value.

How this differs from a join or an index

A JOIN combines rows when you run a query. A foreign key protects the stored data. You can join columns without declaring a foreign key, but the join does not prevent broken references. In a many-to-many relationship, a linking table typically has two foreign keys, one to each of the tables it connects.

An index serves a different purpose: it helps find rows efficiently. PostgreSQL does not automatically index the referencing columns. An index on orders.customer_id can help queries that look up a customer’s orders and help the database find those orders when the customer’s key is updated or the customer is deleted. The trade-off is extra storage and work on writes.

What to expect in an interview

You may be asked to choose a delete rule for two related tables. Start with what the rows represent: deleting a draft order and its line items may make sense, but deleting a customer should not necessarily erase order history. For a composite foreign key, remember that the values must match together in a single referenced row, not separately in different rows.