Learn how foreign keys are used to establish and enforce links between tables.
A Foreign Key is a column or a set of columns in one table that establishes a link between the data in two tables. It acts as a cross-reference between tables because it references the primary key of another table. The table containing the foreign key is called the 'child' or 'referencing' table, and the table containing the primary key it references is called the 'parent' or 'referenced' table. The main purpose of a foreign key is to enforce 'referential integrity'. This is a database rule that ensures that relationships between tables remain consistent. It dictates that a value in the foreign key column of the child table must match a value in the primary key column of the parent table, or the foreign key value must be NULL. For example, consider a 'Products' table with a 'product_id' primary key and an 'Orders' table. The 'Orders' table could have a 'product_id' column that is a foreign key referencing the 'Products' table. This ensures that you cannot create an order for a product that does not exist in the 'Products' table. Foreign keys are the cornerstone of relational database design, allowing us to break down our data into multiple, smaller, well-structured tables (a process called normalization) and then create meaningful relationships between them, accurately modeling the real world.