

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 auto_increment in an already created table in MySQL?
Use ALTER command for this. Let us first create a table −
mysql> create table DemoTable -> ( -> StudentName varchar(100) -> ); Query OK, 0 rows affected (0.46 sec)
Here is the query to insert auto_increment −
mysql> alter table DemoTable ADD COLUMN StudentId int NOT NULL; Query OK, 0 rows affected (0.50 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> alter table DemoTable ADD PRIMARY KEY(StudentId); Query OK, 0 rows affected (1.23 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> alter table DemoTable CHANGE StudentId StudentId int NOT NULL AUTO_INCREMENT; Query OK, 0 rows affected (2.20 sec) Records: 0 Duplicates: 0 Warnings: 0
Insert some records in the table using insert command −
mysql> insert into DemoTable(StudentName) values('Chris'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable(StudentName) values('David'); Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement
mysql> select *from DemoTable;
Output
This will produce the following output −
+-------------+-----------+ | StudentName | StudentId | +-------------+-----------+ | Chris | 1 | | David | 2 | +-------------+-----------+ 2 rows in set (0.00 sec)
- Related Questions & Answers
- How to add a column using MySQL SELECT in an already created table?
- How to make MySQL table primary key auto increment?
- How to create and fill a new column in an already created MySQL table?
- Create a MySQL table from already created table selecting specific rows?
- How to change auto increment number in MySQL?
- How to create a table with auto-increment column in MySQL using JDBC?
- How to randomize an already created vector in R?
- How to add NOT NULL constraint to an already created MySQL column?
- How to auto increment with 1 after deleting data from a MySQL table?
- Auto insert values into a MySQL table in a range?
- How to set auto-increment to an existing column in a table using JDBC API?
- Change the Auto Increment counter in MySQL?
- Passing NULL to MySQL for auto increment?
- How to check an empty table already in a MySQL database?
- How to get the next auto-increment id in MySQL?
Advertisements