Alter a MySQL column to be AUTO_INCREMENT
ALTER TABLE document MODIFY COLUMN document_id INT auto_increment
How to add AUTO_INCREMENT to an existing column?
I think you want to MODIFY
the column as described for the ALTER TABLE
command. It might be something like this:
ALTER TABLE users MODIFY id INTEGER NOT NULL AUTO_INCREMENT;
Before running above ensure that id
column has a Primary index.
ALTER table - adding AUTOINCREMENT in MySQL
CREATE TABLE ALLITEMS(
itemid INT(10)UNSIGNED,
itemname VARCHAR(50)
);
ALTER TABLE ALLITEMS CHANGE itemid itemid INT(10)AUTO_INCREMENT PRIMARY KEY;
DESC ALLITEMS;
INSERT INTO ALLITEMS(itemname)
VALUES
('Apple'),
('Orange'),
('Banana');
SELECT
*
FROM
ALLITEMS;
I was confused with CHANGE
and MODIFY
keywords before too:
ALTER TABLE ALLITEMS CHANGE itemid itemid INT(10)AUTO_INCREMENT PRIMARY KEY;
ALTER TABLE ALLITEMS MODIFY itemid INT(5);
While we are there, also note that AUTO_INCREMENT
can also start with a predefined number:
ALTER TABLE tbl AUTO_INCREMENT = 100;
Insert auto increment primary key to existing table
An ALTER TABLE
statement adding the PRIMARY KEY
column works correctly in my testing:
ALTER TABLE tbl ADD id INT PRIMARY KEY AUTO_INCREMENT;
On a temporary table created for testing purposes, the above statement created the AUTO_INCREMENT
id
column and inserted auto-increment values for each existing row in the table, starting with 1.
mysql add an autoincrement column with start value
No, it works to add an AI column with a starting position. But you almost got the syntax right. Here's a demo:
mysql> CREATE TABLE foo (v varchar(10));
mysql> INSERT INTO foo VALUES ('one'), ('two'), ('three');
Then comes the tricky syntax. You have to declare the column as AUTO_INCREMENT, but then also give the table option for the AUTO_INCREMENT starting value. And you need a comma to separate the ADD COLUMN from the table option.
mysql> ALTER TABLE foo ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY,
AUTO_INCREMENT=999999;
mysql> select * from foo;
+-------+---------+
| v | id |
+-------+---------+
| one | 999999 |
| two | 1000000 |
| three | 1000001 |
+-------+---------+
Related Topics
In Sql, What's the Difference Between Count(Column) and Count(*)
Calculating Cumulative Sum in Postgresql
How to Select from Subquery Using Laravel Query Builder
Passing an Array of Parameters to a Stored Procedure
How to Delete Duplicate Rows Without Unique Identifier
Pass Multiple Values in Single Parameter
How to Introduce Multiple Conditions in Like Operator
Date Difference Between Consecutive Rows
SQL Server - Stop or Break Execution of a SQL Script
How to Use (Install) Dblink in Postgresql
How to Emulate SQLs Rank Functions in R
SQL Rownum How to Return Rows Between a Specific Range
Sqlite Database Default Time Value 'Now'