Primary Key vs Foreign Key Explained
Q: Can you explain the difference between a primary key and a foreign key in a database?
- SQL Developer
- Junior level question
Explore all the latest SQL Developer interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create SQL Developer interview for FREE!
A primary key is a unique identifier for a record in a database table. It ensures that each entry can be distinguished from all others and cannot contain null values. For example, in a table called "Employees," the "EmployeeID" might be designated as the primary key because each employee has a unique ID.
On the other hand, a foreign key is a field in one table that links to the primary key of another table. It establishes a relationship between the two tables and helps maintain referential integrity. For instance, in a "Departments" table, if we have a foreign key "DepartmentID" in the "Employees" table that points to the "DepartmentID" primary key in the "Departments" table, it signifies that each employee belongs to a specific department.
In summary, the primary key uniquely identifies records within its own table, while the foreign key creates a link to the primary key from another table, thus enabling relationships between data.
On the other hand, a foreign key is a field in one table that links to the primary key of another table. It establishes a relationship between the two tables and helps maintain referential integrity. For instance, in a "Departments" table, if we have a foreign key "DepartmentID" in the "Employees" table that points to the "DepartmentID" primary key in the "Departments" table, it signifies that each employee belongs to a specific department.
In summary, the primary key uniquely identifies records within its own table, while the foreign key creates a link to the primary key from another table, thus enabling relationships between data.


