What is a foreign key?
A foreign key is a field in one table that refers to the primary key of another table. It links the tables to create a relationship, usually one-to-many, and supports referential integrity: a foreign key value must match an existing primary key value. Example: A Loan table records which member borrowed which book. Tables: Member(memberID, name) and Loan(loanID, memberID, bookTitle). memberID in Loan matches the primary key of Member. Answer: memberID is the foreign key in Loan, linking each loan to one member.
In SQA Higher Computing Science (Database design and development), you design relational databases with primary and foreign keys, show relationships in entity-relationship diagrams and apply referential integrity. One member can have many loans, so the foreign key sits on the "many" side.
Worked example
Tables: Member(memberID, name) and Loan(loanID, memberID, bookTitle). Identify the foreign key and the relationship.
- Find each primary key: memberID in Member, loanID in Loan.
- Look for a field in Loan that matches another table's primary key: memberID.
- So memberID in Loan is the foreign key.
- One member can have many loans, so the relationship is one-to-many.
Answer: memberID is the foreign key in Loan, creating a one-to-many relationship from Member to Loan.
Want one-to-one support?
One-to-one online tuition can help you build confidence in your subject. Find a tutor who teaches your course.
Find a TutorLearn face to face in Glasgow
Prefer in-person lessons? Visit the ExpertTutor Glasgow Southside centre.
See the centre