A primary key is basically a column in a database table, which can only have unique values in the individual fields. Further, it cannot contain NULL values.
A single table will contain only one Primary Key, which can correspond to single or multiple fields. MySQL primary keys are actually implemented to avoid duplication within a database table
In this tutorial we will learn to create MySQL primary key.
Step 1 – Switching to Appropriate Database
In MySQL, primary key is applied on a particular field of the table.
So for that, we have to start with creating a table.
Over here, we have to specify in which database we will create the table. In our case, it is an HR database, hence, type the following:
use HR
and hit enter
Step 2 – Writing the Query
Now let’s start creating the table. Over here, we will name the table “Products” and it will have an identification field which we would name as “Product ID”. This will be our primary key so for that we have to insert two keywords, NOT NULL and AUTO INCREMENT. Since we want numeric values for this field, we will give it the data type integer.
Next, add a column for the product name. Let us define its data type as VarChar and set its maximum length as 50.
After that, write the PRIMARY KEY keyword and specify the ID field within parenthesis. Insert a closing bracket followed by a semi colon in the end and hit Enter. Complete query would be:
create table products
(
prod_id INT NOT NULL AUTO_INCREMENT,
product_name VARCHAR(50),
PRIMARY KEY(prod_id)
);
And that is how we can create MySQL primary keys.