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

Ready to Build Something Real?

We give you the skills to build, deploy, and own a full product. Professional stack, AI co-pilot, no coding background required.