How to insert own values into auto_increment column in MySQL?

MySQLMySQLi Database

You can achieve this with the help of INSERT statement i.e, you can simply insert it like a normal insert. The syntax is as follows −

INSERT INTO yourTableName (yourIdColumnName,yourColumnName) values(value1,'value2');
Let us first create a table:
mysql> create table InsertValueInAutoIncrement
   -> (
   -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> UserName varchar(20)
   -> );
Query OK, 0 rows affected (0.59 sec)

Now you can insert some records in the table using insert command. Here, we are also inserting our own values for the auto_increment field UserId. The query is as follows −

mysql> insert into InsertValueInAutoIncrement(UserName) values('John');
Query OK, 1 row affected (0.19 sec)
mysql> insert into InsertValueInAutoIncrement(UserName) values('Carol');
Query OK, 1 row affected (0.17 sec)
mysql> insert into InsertValueInAutoIncrement(UserName) values('Sam');
Query OK, 1 row affected (0.11 sec)
mysql> insert into InsertValueInAutoIncrement(UserName) values('Bob');
Query OK, 1 row affected (0.18 sec)
mysql> insert into InsertValueInAutoIncrement(UserId,UserName) values(100,'Maxwell');
Query OK, 1 row affected (0.18 sec)
mysql> insert into InsertValueInAutoIncrement(UserName) values('James');
Query OK, 1 row affected (0.20 sec)
mysql> insert into InsertValueInAutoIncrement(UserId,UserName) values(1000,'Larry');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using a select statement. The query is as follows −

mysql> select *from InsertValueInAutoIncrement;

The following is the table −

+--------+----------+
| UserId | UserName |
+--------+----------+
|      1 | John     |
|      2 | Carol    |
|      3 | Sam      |
|      4 | Bob      |
|    100 | Maxwell  |
|    101 | James    |
|   1000 | Larry    |
+--------+----------+
7 rows in set (0.00 sec)
raja
Published on 19-Mar-2019 07:24:37
Advertisements