What is a foreign key in a database?
A foreign key is an attribute in one table that matches the primary key of another table. It links the two tables together. Using foreign keys keeps the link accurate, because each value must match an existing primary key (referential integrity). Example: the Pupil table has the attribute clubID. clubID is the primary key of the Club table. Pupil 1 has clubID C1, which matches Chess. Answer: clubID is the foreign key in Pupil.
Quick answer: A foreign key is an attribute in one table that is the primary key of another table, and it links the two tables. This page covers National 5 Computing Science, SQA (C816 75), Database design and development: design (data dictionary).
Key terms
- Primary key: an attribute that uniquely identifies each record in its own table.
- Foreign key: an attribute that holds the primary key of a linked table. Values can repeat in the foreign key attribute.
- Referential integrity: every foreign key value must match a primary key value in the linked table.
- A National 5 data dictionary lists the entity name, attribute name, key, type, size and validation for each attribute.
Extra example
A school stores pupils and clubs. Identify the foreign key and show how the tables join.
- Club (clubID, clubName) has the primary key clubID.
- Pupil (pupilID, surname, clubID) has the primary key pupilID.
- clubID in Pupil matches the primary key of Club, so it is the foreign key.
- An equi-join links the tables:
SELECT Pupil.surname, Club.clubName
FROM Pupil, Club
WHERE Pupil.clubID = Club.clubID
ORDER BY Pupil.surname;Answer: clubID is the foreign key. The query returns Ahmed (Drama), Hunter (Chess) and Reid (Chess).
Want one-to-one help? Find an online Computer Science tutor with ExpertTutor.
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