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

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.