Foreign Keys and References
You'll learn how foreign keys link tables together by pointing to primary keys in other tables, forming the backbone of relational database design.
What Are Foreign Keys?
A foreign key is a column (or set of columns) in one table that references the primary key of another table. Think of it like a pointer or citation: just as a research paper cites other papers to establish connections, a foreign key creates a relationship between two tables by "citing" rows in another table.
Foreign keys enforce referential integrity, meaning the database ensures that relationships remain valid. You can't reference a row that doesn't exist—like trying to assign an employee to a department that hasn't been created yet.
How They Work
Imagine two tables:
Departments table:
department_id(Primary Key)department_name
Employees table:
employee_id(Primary Key)employee_namedepartment_id(Foreign Key → references Departments)
The department_id in the Employees table is a foreign key. It must match a valid department_id from the Departments table. This creates a relationship: each employee belongs to exactly one department.
Why Use Foreign Keys?
Foreign keys provide two critical benefits:
- Data Integrity: The database prevents "orphaned" records (e.g., an employee assigned to a non-existent department)
- Relationships: They model real-world connections between entities (employees work in departments, orders contain products, etc.)
Without foreign keys, you'd have to manually verify relationships in your application code—error-prone and inefficient.
Key Takeaway: Foreign keys establish relationships between tables by referencing primary keys in other tables, ensuring data consistency and modeling real-world connections in your database.