Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Add Auto Increment in MySQL Table



To add AUTOINCREMENT in MySQL, you can use the ALTER command.

ALTER TABLE yourTableName change yourColumName yourColumnName dataType AUTO_INCREMENT PRIMARY KEY;

To understand the above concept, create a table with a column. Let us create a table −

mysql> create table AlterTableToAddAutoIncrement
   -> (
   -> StudentId int
   -> );
Query OK, 0 rows affected (0.57 sec)

Implement the above syntax to change “StudentId” with AUTOINCREMENT. The query is as follows −

mysql> alter table AlterTableToAddAutoIncrement change StudentId StudentId int AUTO_INCREMENT Primary  key;
Query OK, 0 rows affected (1.93 sec)
Records: 0 Duplicates: 0 Warnings: 0

We have added AUTO_INCREMENT to column name ‘StudentId’. Now you can verify whether autoincrement is working or not by inserting records without giving any value.

The query is as follows −

mysql> insert into AlterTableToAddAutoIncrement values();
Query OK, 1 row affected (0.16 sec)
mysql> insert into AlterTableToAddAutoIncrement values();
Query OK, 1 row affected (0.16 sec)
mysql> insert into AlterTableToAddAutoIncrement values();
Query OK, 1 row affected (0.33 sec)

Now you can display all records which will be displayed in sequence of 1, 2, 3, 4, etc. The query is as follows −

mysql> select *from AlterTableToAddAutoIncrement;

The following is the output −

+-----------+
| StudentId |
+-----------+
|         1 |
|         2 |
|         3 |
+-----------+
3 rows in set (0.00 sec)
Updated on: 2019-07-30T22:30:24+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements