SQL
6. Keys

Keys are used to establish relationships between tables in a database. They are used to uniquely identify records in a table and to establish relationships between tables. There are several types of keys in SQL, each with its own purpose.

  • Rows in a table are known as tuple.
  • Columns in a table are known as attributes.

Consider the following table employee:

emp_idemp_nameemp_salaryemp_mobile_numberemp_age
1Alice50000987654321030
2Bob60000876543210935
3Charlie70000765432109840

1. Primary Key

So according to the above table we can see that emp_id is unique for each employee. So, emp_id can be used as a primary key for the table employee.

A primary key is a column or a set of columns that uniquely identifies each record in a table. It must contain unique values and cannot contain NULL values. A table can have only one primary key.

2. Foreign Key

Consider the following tables employee and department:

Employee Table:

emp_idemp_nameemp_salaryemp_mobile_numberemp_age
1Alice50000987654321030
2Bob60000876543210935
3Charlie70000765432109840

Department Table:

emp_iddepartment_namedepartment_location
1HRNew York
2FinanceLondon
3ITTokyo

In the above table department, emp_id is a foreign key.

💡

A foreign key is a column or a set of columns in a table that establishes a relationship with a primary key in another table. It is used to link two tables together.

Here the employee table is known as the Base / Referenced Table and the department table is known as the Referencing Table.