Quick Reach
What is primary key in MySQL
In the previous chapter, we looked at creating MySQL tables. We simply created a table (tbl_employee) for our example with four columns. The table had four columns as follows:
- emp_name
- emp_age
- emp_salary
- joining_date
An example of a table with primary key
Now consider a scenario where two employees with similar names join at the same date, how you will differentiate both? You have to create a key that differentiates between two or more records. There can be many other scenarios where you will need to differentiate records while working with databases. This is where a primary key is important.
A primary key is a field or column in a table that cannot contain duplicate values or it uniquely identifies each row in a table.
A MySQL primary key example
To demonstrate the primary key in MySQL, we will use the same table as mentioned earlier (tbl_employee). The table will be created with above mentioned four columns as well as an emp_id as a primary key. See the following command to learn how we may create a primary key:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
Create table tbl_employee
(emp_id int,
emp_name varchar(100),
emp_age int,
emp_salary decimal(8,2),
joining_date datetime,
PRIMARY KEY (emp_id)
);
|
The MySQL command will create a table, tbl_employee with five fields including a primary key, emp_id.
Example of primary key in an existing table
You can also create a primary key in an existing table by using the Alter table statement of MySQL. To make it clearer, consider we have a table without a primary key as shown below:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
Create table tbl_employee
(emp_id int,
emp_name varchar(100),
emp_age int,
emp_salary decimal(8,2),
joining_date datetime
);
|
Using Alter statement to add a primary key
Now we will use the Alter Table statement to create a primary key as follows:
1
|
ALTER TABLE tbl_employee ADD PRIMARY KEY (emp_id);
|
Note that, in order to make the emp_id field as a primary key, it must have been created with NOT NULL constraint. If it was created as a NULL, the above statement will produce an error.
Also see: MySQL create table
Leave A Comment?