/  Technology   /  Add Primary key to the Existing Table In MYSQL

Add Primary key to the Existing Table In MYSQL

 

To add a primary key to a table column, follow these steps in order:

  1. Create a database in the system.
  2. Create the table in the SQL database.
  3. View the table structure.
  4. Add the primary key to column in the table.
  5. View the table structure.

The following steps will be explained with an example.

Create a Database

A structured query language begins with creating a database to store structured tables.

To create a database, use the following SQL syntax:

CREATE DATABASE Database_Name;  

Let’s say you want to create a database of students. In Structured Query Language, type the following command:

CREATE DATABASE students;

Create a Table and Insert the data

For creating a table in your database, you need to use the following SQL syntax:

CREATE TABLE table_name    

column_Name_1 data type (size of the column_1),    
column_Name_2 data type (size of the column_2),    
column_Name_3 data type (size of the column_3),    
...    
column_Name_N data type (size of the column_1)  
);    

Let’s say you want to create the student_details table in the Students database. You will need to type the following query in your SQL application:

CREATE TABLE student_details (
ID INT ,
LastName varchar(255),
FirstName varchar(255),
City varchar(255)
);

View the Table Structure before Primary key Addition

To view the structure of the Cars table, type the following query in your SQL application after you have created the table and inserted data:

DESCRIBE student_details ;

Add Primary key to the Existing Table

In SQL, you have to use the following ALTER syntax if you want to add a primary key to an existing table:

ALTER TABLE Table_Name ADD CONSTRAINT Constraint_Name PRIMARY KEY (Column_Name);  

When the student_details table already exists in the database system, the following query adds a PRIMARY KEY constraint on the id column:

ALTER TABLE student_details ADD CONSTRAINT id_prmrykey PRIMARY KEY ( id);

 

Leave a comment