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.

Read more

SQL UNIQUE Constraint

The UNIQUE constraint is used to uniquely identify each row in a database table. It is some similar to Primary key, but has some difference:

  • Primary Key is automatically Unique Constraint
  • One table should have ONE primary key, but could have mutiple Unique Constraint

Read more