Home » SQL

SQL query to add primary key

In this article, we are going to learn how to write a SQL Query to add primary key to a column?
Submitted by Manu Jemini, on March 14, 2018

Primary key: This key is used to define the uniqueness of column as there always should be a unique row of data for this column.

This is very important to have one primary key. A primary key is a property of a column, which defines that the column will have unique values.

The Simple yet powerful example of this concept is Roll Number of a student. The Roll Number always contains unique value every time.

Why is primary key so important? Well, there are multiple answers to it, but what, one of the less discussed argument is that primary key help to connect different table together very easily. This gives us so much power that we should not worry about the space, as whenever we need to use the record all we will do is use the primary key.

Table (employee) having three fields and four data in it,

    Id		Name		Address

    100		Aman		Mumbai
    200		Arun		Pune
    300		Karan		Delhi
    400		Aman		Mumbai

As we can see the above table have three columns, they did not define as a primary key but suppose we need to add a primary key on column id the all we need to do is, use alter table and modify the column to add a primary key with the name of the column as the parameter in it.

Query 1:

ALTER TABLE employee 
MODIFY COLUMN 'id' INT(10) 
UNSIGNED NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY ('id');

Output:

SQL query to add primary key



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.