Home >Database >Mysql Tutorial >How to Add AUTO_INCREMENT to an Existing MySQL Column?
Adding AUTO_INCREMENT to an Existing MySQL Column: A Step-by-Step Guide
Need to add an auto-incrementing feature to an existing MySQL column? This guide shows you how to modify your table and add the AUTO_INCREMENT
constraint to your primary key column. This is particularly helpful when a table was initially created without auto-increment functionality and you need to add it later.
The SQL Command
The core SQL command to achieve this is:
<code class="language-sql">ALTER TABLE table_name MODIFY COLUMN column_name INT auto_increment;</code>
Illustrative Example
Let's say you have a document
table and want to make the document_id
column auto-increment. The SQL statement would be:
<code class="language-sql">ALTER TABLE document MODIFY COLUMN document_id INT auto_increment;</code>
Important Consideration:
Remember, you cannot add AUTO_INCREMENT
to a column that already contains data. Before executing the above command, you must first clear all existing data from the target column. Otherwise, the operation will fail.
The above is the detailed content of How to Add AUTO_INCREMENT to an Existing MySQL Column?. For more information, please follow other related articles on the PHP Chinese website!