A foreign key in a database is a column or set of columns in one table that refers to the primary key in another table. Even so, it is a way to create a relationship between two tables, often called the child table and the parent table. The foreign key helps enforce referential integrity, which means the database will not allow a record to exist in the child table if there is no matching record in the parent table. In simple terms, a foreign key is like a pointer that keeps related data connected and consistent.
Introduction
When people first learn about databases, they often start with single tables. Because of that, a single table can store all the information needed for one type of object, such as customers or products. But real applications usually need multiple tables. Take this: an e-commerce app may have a Customers table and an Orders table. In practice, the Orders table needs customer information, but it should not store a customer’s full address every time an order is placed. Instead, it can store a customer ID that points to the Customers table.
That customer ID is often created using a foreign key. The foreign key in the Orders table references the primary key in the Customers table. This relationship helps the database keep data accurate and prevents orphaned records.