views:

308

answers:

5

How do I change the amount auto_increment fields in MySQL increment by from the default (1) to n?

+4  A: 

You can change it using ALTER TABLE:

ALTER TABLE table AUTO_INCREMENT = n;

Or if you want to do set it from start:

CREATE TABLE table (...) AUTO_INCREMENT = n;
Lukáš Lalinský
I don't *think* that does what he wants (it answers the question he asks in the body of his question, but not the question in the title). The question is definitely ambiguous though.
Dominic Rodger
Yep, this doesn't do what he's trying to do (I've now edited the question to hopefully make it clearer).
Dominic Rodger
+2  A: 

If you want to change autoincrement step from 1 to N then there is a solution. It could be done on MySQL server side: look for '--auto-increment-increment' startup option or use following command SET @@auto_increment_increment=2;, but be warned that this is a server wide change (all tables will increment by 2).

Unortodox solutions could that could be considered:

  1. Launch two MySQL servers on same machine, with different ports (one with auto_increment_increment=1 other with auto_increment_increment=2)
  2. Use some serverside magic (PHP, ASP ,???) combined with turning off tables auto_increment to manually calculate (simple peek at last id and +=2 would be ok) and provide id in INSERT query.

Some official MySQL FAQ

mth
hi, i checked the faq i am little bit confused [you can set each server to generate auto-increment values that don't conflict with other servers. The --auto-increment-increment value should be greater than the number of servers (from that page)] could any body explain this?
sansknwoledge
the idea is this: servers={db1,db2,db3}; db01:{--auto-increment-offset=0;--auto-increment-increment=3};db02:{--auto-increment-offset=1;--auto-increment-increment=3};db03:{--auto-increment-offset=2;--auto-increment-increment=3};so, db1 only generates IDs where (n % 3) == 0, for db2 (n % 3) == 1, for db3 (n % 3) == 2; i.e. db1:"3,6,9,..." db2:"1,4,7,..." db3:"2,5,8" -> no id conflict
Piskvor
@Piskvor thanks for the clarification, but if i am having more than one table in my db all with autogenerate columns and i want only one table to increment in steps of say 2 and rest follow 3 what should i do?
sansknwoledge
A: 
alter table <table name>  auto_increment=n

where n is the number you want to start

Treby
A: 

You can also use ALTER SEQUENCE sequence_name INCREMENT BY N where N is the new incremnent value.

Sachin Chourasiya
-1 This doesn't apply to MySQL.
Lukáš Lalinský
Oh, Its a big mistake
Sachin Chourasiya
+1  A: 

thanks to all, @molevna , so i think this feature is not currently available in mysql. adjusting autoincrement in serverwide is not feasible as per your warning, so i am going back the old way of hardcoding in my ui. thanks to all once again.

sansknwoledge