How can we apply AUTO_INCREMENT to a column?


AUTO_INCREMENT means that the column will get the value automatically. To illustrate it we have created a table ‘employees’ as follows −

mysql> Show Create Table employees\G

*************************** 1. row ***************************
Table: employees

Create Table: CREATE TABLE `employees` (
   `Id` int(11) NOT NULL AUTO_INCREMENT,
   `Name` varchar(35) DEFAULT NULL,
   PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

1 row in set (0.00 sec)

From the above result set, we can see that column id is given the auto-increment option. Now, when we will insert the value in Name field, the id field will get the values automatically −

mysql> Insert Into employees(Name) Values('Ram');
Query OK, 1 row affected (0.09 sec)

mysql> Insert Into employees(Name) Values('Shyam');
Query OK, 1 row affected (0.03 sec)

mysql> Insert Into employees(Name) Values('Mohan');
Query OK, 1 row affected (0.04 sec)

mysql> Insert Into employees(Name) Values('Sohan');
Query OK, 1 row affected (0.04 sec)

mysql> Select * from employees;

+----+-------+
| Id | Name  |
+----+-------+
| 1  | Ram   |
| 2  | Shyam |
| 3  | Mohan |
| 4  | Sohan |
+----+-------+

4 rows in set (0.00 sec)

Updated on: 30-Jul-2019

117 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements