Foreign Key and Referential Integrity
Fast recall
Quick revision
Core answer
Understanding how foreign key constraints enforce referential integrity at the database level and prevent inconsistent data states
Thinking foreign keys are just a naming convention or application-level concept, rather than database-enforced constraints that block invalid operations
Foreign keys can reference a primary or UNIQUE candidate key; JPA maps the relationship, while the schema constraint enforces it for every writer
Interview-ready guide
Interview answer
A foreign key is one or more child-table columns that reference a primary key or another UNIQUE candidate key.
id`. Each non-NULL customer ID must match a real customer, so the database rejects an order for customer 999 when that customer does not exist. It also checks parent updates and deletes.
The configured referential action decides whether such a change is blocked, cascades to the children, or sets a nullable child key to NULL. SQL's default is NO ACTION, while exact timing and support vary by database. In JPA, @ManyToOne and @JoinColumn map the Java relationship, but the database enforces it only when schema generation or a migration creates the actual foreign-key constraint.
Indexing is a separate decision: InnoDB requires a suitable child index and may create one, whereas PostgreSQL does not create that child index automatically. I would check the real join and parent-update workload before adding or removing it.
Foreign Key and Referential Integrity
Direct Answer
A foreign key is one or more columns that reference a primary key or another UNIQUE candidate key. For each non-NULL foreign-key value, the database checks that a matching referenced row exists. It also blocks or applies the configured action to parent updates and deletes, which prevents broken references.
Code Example
import jakarta.persistence.*;
@Entity
@Table(name = "orders")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY) // Foreign key relationship
@JoinColumn(name = "customer_id", nullable = false)
private Customer customer; // Hibernate maps this to customer_id column
private Double totalAmount;
private String status;
}
// The database enforces this at the schema level:
// ALTER TABLE orders
// ADD CONSTRAINT fk_orders_customer
// FOREIGN KEY (customer_id)
// REFERENCES customers(id)
// ON DELETE RESTRICT; // Prevents deleting customers with orders
Common Mistakes & Pitfalls
- Treating the JPA mapping as the constraint:
@ManyToOneand@JoinColumndescribe the object-relational mapping. A real database constraint exists only when the schema or migration creates it, so verify the generated DDL or migration. - Assuming every database handles indexes the same way: InnoDB requires a suitable index on the child columns and may create one automatically. PostgreSQL does not automatically create an index on the referencing columns. Add or keep an index when joins, parent deletes, or updates in the actual workload benefit from it.
- Ignoring referential actions: SQL uses
NO ACTIONwhen no action is specified, but databases differ in timing and in how they treatNO ACTIONandRESTRICT. ChooseCASCADE,SET NULL, or a blocking action deliberately;SET NULLalso requires nullable child columns.
Check your understanding
Answer these without looking back at the article.
- Can a foreign key be NULL?
- What is an orphaned record?
- What is the difference between ON DELETE CASCADE and ON DELETE RESTRICT?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.