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):
And we have another table Project:
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.
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
The PRIMARY KEY constraint is used to identify each row in a database table. It has some features:
- It must be unique value
- One table should have ONE primary key.
- One table should ONLY have one primary key.
The SQL DEFAULT Constraint is used to set a default value to a column when we insert a new row to a table without providing a value for the column.
We can use the DEFAULT keyword to specify a default value for a column.
By default, a column can hold NULL value. The SQL NOT NULL Constraint is used to force a column cannot accept a NULL value, and must hold a value.
SQL table is a place where the SQL database stores the data. It has columns and rows. We can use CREATE TABLE statement to create a table in a database.