Primary Key | - It identifies each row or record uniquely in a database table.
- It cannot have NULL values.
- A table can have only one primary key.
- It contains unique values.
- If a table has a primary key, then you cannot have two records of same value.
For Example: Empid INT PRIMARY KEY,
- In the above example, there is one Employee table where Empid have a Primary Key.
- When multiple fields are used as a primary key, is called as Composite key.
Syntax: PRIMARY KEY (column1, column2);
|
Foreign Key | - Foreign key is a logical rule about values in multiple columns or in tables.
- It is a set of columns in a table.
- It requires to match at least one primary key of a row in another table.
- It defines the relationship between the tables.
- The 'references' keyword is used while referencing the column into the another table.
For example: Empid INT PRIMARY KEY, FOREIGN KEY (Empid) references Department (Empid);
- In the above example, there are two tables Employee and Department. The 'Empid' in Employee table has a primary key. In Department table, it takes reference of 'Empid' from Employee table using Foreign key with the keyword 'references'.
|
Unique Key | - It prevents two records from having identical values in a particular column.
- It identifies each record uniquely in a database table.
- Primary key and Unique key both provide a guarantee of uniqueness for a column.
- Primary key has a unique constraint automatically defined on it.
Note: Important thing to understand about the primary key and unique key, is that a table can have many unique constraints, but only one primary key can have per table.
- Unique key is declared with 'NOT NULL' constraint at the time of creating a table.
- It accepts only one NULL value.
- It is a unique non-clustered index.
|
Check Constraint | - It enables a condition to check the value being entered into a record.
For example: Age INT NOT NULL CHECK (Age >= 19)
- Multiple Check constraints are used in a single column.
- It returns true or false result based on the logical operator according to Boolean (logical) expression.
|