Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ALTER table - adding AUTOINCREMENT in MySQL

I created a table in MySQL with on column itemID.

After creating the table, now I want to change this column to AUTOINCREMENT.

How can this be done using ALTER statements?

Table definition:

ALLITEMS (itemid int(10) unsigned, itemname varchar(50))

I am using the following code but it is throwing a syntax error

Error: syntax incorrect.

ALTER TABLE allitems MODIFY itemid INT(10) UNSIGNED AUTOINCREMENT;  
like image 271
sumit Avatar asked Aug 05 '11 13:08

sumit


People also ask

How do I add an autoincrement to a table?

Syntax for MySQL MySQL uses the AUTO_INCREMENT keyword to perform an auto-increment feature. By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record. VALUES ('Lars','Monsen'); The SQL statement above would insert a new record into the "Persons" table.

How do you set a field as auto increment in MySQL?

In MySQL, the syntax to change the starting value for an AUTO_INCREMENT column using the ALTER TABLE statement is: ALTER TABLE table_name AUTO_INCREMENT = start_value; table_name.

Can we have 2 auto increment in MySQL?

You can't have two auto-increment columns.

How do I create an autonumber in MySQL?

You can set the MySQL Auto Increment Primary Key field via the following syntax: CREATE TABLE table_name ( column1 datatype NOT NULL AUTO_INCREMENT, column2 datatype [ NULL | NOT NULL ], ... );


2 Answers

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; 
like image 183
ThinkCode Avatar answered Sep 25 '22 14:09

ThinkCode


The syntax:

   ALTER TABLE `table1` CHANGE `itemId` `itemId` INT( 11 ) NOT NULL AUTO_INCREMENT  

But the table needs a defined key (ex primary key on itemId).

like image 35
blejzz Avatar answered Sep 21 '22 14:09

blejzz