Alter a MySQL column to be AUTO_INCREMENT
I’m trying to modify a table to make its primary key column AUTO_INCREMENT
after the fact. I have tried the following SQL, but got a syntax error notification.
ALTER TABLE document
ALTER COLUMN document_id AUTO_INCREMENT
Am I doing something wrong or is this not possible?
+--------------------+ | VERSION() | +--------------------+ | 5.0.75-0ubuntu10.2 | +--------------------+
ALTER TABLE document MODIFY COLUMN document_id INT auto_increment
Roman is right, but note that the auto_increment column must be part of the PRIMARY KEY or a UNIQUE KEY (and in almost 100% of the cases, it should be the only column that makes up the PRIMARY KEY):
ALTER TABLE document MODIFY document_id INT AUTO_INCREMENT PRIMARY KEY
In my case it only worked when I put not null
. I think this is a constraint.
ALTER TABLE document MODIFY COLUMN document_id INT NOT NULL AUTO_INCREMENT;
The SQL to do this would be:
ALTER TABLE `document` MODIFY COLUMN `document_id` INT AUTO_INCREMENT;
There are a couple of reasons that your SQL might not work. First, you must re-specify the data type (INT
in this case). Also, the column you are trying to alter must be indexed (it does not have to be the primary key, but usually that is what you would want). Furthermore, there can only be one AUTO_INCREMENT
column for each table. So, you may wish to run the following SQL (if your column is not indexed):
ALTER TABLE `document` MODIFY `document_id` INT AUTO_INCREMENT PRIMARY KEY;
You can find more information in the MySQL documentation: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html for the modify column syntax and http://dev.mysql.com/doc/refman/5.1/en/create-table.html for more information about specifying columns.