SQL FOREIGN KEY Constraint

The FOREIGN KEY constraint is used to point to primary key of another database table. Foreigh key ensures that the data exists when we have reference to it.

For example, we have a table of Employee (EmployeeId is Primary):

EmployeeId FirstName LastName
1 Mkai Khaao
2 Hiaf Lihaaa

And we have another table Project:

ProjectId ProjectName ProjectManagerId
1 Basic Project 1
2 Premium Project 2

The ProjectManagerId in table Project points to EmployeeId in table Employee. That means only an exist employee can be as a project manager. If you try to set ProjectManagerId=3, it will fail, because it doesn’t have an employee with EmployeeId=3.

Continue reading