- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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;
+----+---------+------+ | 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.
- How to make MySQL table primary key auto increment?
- How to insert data into a table with auto-incremented columns using JDBC?
- Reserving MySQL auto-incremented IDs?
- Two columns as primary key with auto-increment in MySQL?
- Query MySQL database to echo highest auto incremented number?
- How to change a primary key in MySQL to auto_increment?
- Remove Primary Key in MySQL?
- Reset Primary Key in MySQL
- How to get primary key value (auto-generated keys) from inserted queries using JDBC?
- How to get primary key of a table in MySQL?
- How to retrieve auto-incremented value generated by PreparedStatement using JDBC?
- How to retrieve auto-incremented value generated by Statement using JDBC?
- Reset the primary key to 1 after deleting all the data in MySQL?
- How to set the initial value of an auto-incremented column in MySQL using JDBC?
- How to remove primary key from MongoDB?