How to insert data to MySQL having auto incremented primary key?


Whenever your column has an auto incremented primary key then there is an advantage that you do not need to give value for that column in the INSERT command. This means MySQL will give the value for that column.

To understand the above concept, let us first create a table. The query to create a table is as follows −

mysql> create table AutoIncrementedPrimary
   -> (
   -> Id int auto_increment,
   -> Name varchar(100),
   -> Age int,
   -> Primary key(Id)
   -> );
Query OK, 0 rows affected (0.56 sec)

Now insert records for the column Name and Age only, MySQL will provide the value for Id column on its own since it is set auto_increment. The query to insert record is as follows −

mysql> insert into AutoIncrementedPrimary(Name,Age) values('John',23);
Query OK, 1 row affected (0.12 sec)

mysql> insert into AutoIncrementedPrimary(Name,Age) values('Sam',24);
Query OK, 1 row affected (0.15 sec)

mysql> insert into AutoIncrementedPrimary(Name,Age) values('Carol',30);
Query OK, 1 row affected (0.13 sec)

mysql> insert into AutoIncrementedPrimary(Name,Age) values('Johnson',28);
Query OK, 1 row affected (0.16 sec)

Let us now display all records from the table using select command. The query is as follows −

mysql> select *from AutoIncrementedPrimary;

Output

+----+---------+------+
| Id | Name    | Age  |
+----+---------+------+
|  1 | John    |   23 |
|  2 | Sam     |   24 |
|  3 | Carol   |   30 |
|  4 | Johnson |   28 |
+----+---------+------+
4 rows in set (0.00 sec)

Look at the above sample output, the column Id value is provided by MySQL.

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements