Primary Key in DBMS: A primary key is the minimal set of columns in the database table, which uniquely identifies each row or tuple in that table. Any table in the database cannot contain more than one primary key. All the values are different from each other in the column, which is defined as the primary key.
It is a key that is a distinct identifier for a record in the database. When we created the table, we typically have to assign the one column or field as the primary key.
Following are the two characteristics of the Primary key in DBMS:
- In the table, two tuples cannot have the same value, i.e., duplicate values cannot exist.
- The field or column, which is defined as the primary key, cannot have a NULL value.
- There is only one primary can be assigned in a table.
We are describing the primary key with the following example, so you can easily understand it.
This example uses one table Employee, which contains four columns or fields. The name of four columns is Employee_ID, Employee_Name, Employee_Age, Employee_Salary. Out of these four columns, one column or set of more than one column can be a primary key.
In the table, we cannot define the primary key to Employee_Name, because more than one employee in the table can have the same name. As well as, we cannot define the primary key to Employee_Age and Employee_Salary because, in the table, more than one employee can have the same age and same salary.
So, we have to only define the Employee_ID as the primary key, because each employee has a unique ID, which uniquely identifies employee record in the table.
|Employee_ID (Primary Key)||Employee_Name||Employee_Age||Employee_Salary|
Create the Primary Key in RDBMS
We have learned the meaning of the primary key with the example. Now, we will discuss how to create the primary key in the SQL. So, we will take the above table to create the primary key. In SQL, we can create the primary key as shown below:
Create table Employee
Employee_Id int primary key,
Employee_Name varchar(255) not null,
Employee_Age int not null,
Employee_Salary int not null
If we do not define the primary key to the field at the time of table creation, then we can also define it later as same as shown below:
ALTER TABLE Employee
ADD CONSTRAINT PK_Employee PRIMARY KEY (Employee_ID);