Backendintermediate

Foreign Key

A column in one database table that references a row in another table, creating a relationship between them.

Detailed Explanation

A foreign key is a column in one table that references the primary key of another table, creating relationships between tables. If a posts table has a user_id column that references the users table's id, user_id is a foreign key.

Foreign keys ensure referential integrity—you cannot create a post for a non-existent user. If you delete a user, the Database can automatically delete their posts (or prevent deletion if they have posts). Foreign keys make relationships explicit and safe. You define them using SQL when creating or altering tables.

Foreign keys are fundamental for relational databases. They prevent orphaned data (data without a parent) and enforce constraints. Understanding them is essential for database design.

Foreign keys are often used alongside database triggers (e.g., a trigger on the comments table that looks up the post author via a foreign key) and indexes for query performance.

Code Example

sql
Free forever

Start building software you actually own.

Learn the concepts, fix things with confidence, and ship real products with AI beside you. No coding background required, and we're with you from the first idea to launch.

Free to start. No card. Leave whenever you want.