I’m using MySQL to make a table:
CREATE TABLE school.student(
Std_id INT NOT NULL AUTO_INCREMENT,
Std_name CHAR(40) NOT NULL,
Std_Birth DATE,
Std_Group CHAR(2) check(Std_Group in ('G1', 'G2','G3','G4'))
);
And I’m trying to make the auto increment start from 1000 and increment by two (1000, 1002, 1004, 1006, etc.) while using CREATE.
4
Answers
You may try this solution:
while you set the value of @@auto_increment_increment, it will
affect all over the database. Because, it’s a global variable for
MySQL.
For setting the starting value from 1000, you may need to set
AUTO_INCREMENT at the end of the Create Table syntax.
You can do it as follows:
select case when count(Std_id) >= 1 then max(Std_id) + 2 else 1000 end
: this will check if there are any records in your table. If not, it will insert the first with id 1000.You can start the auto_increment for a given table at 1000 with a table option:
Note that the next id generated will be one greater than the table option is set to, so it will generate value 1001. If you want it to include the value 1000, set the table option
AUTO_INCREMENT=999
.Your other requirement is more difficult.
https://dev.mysql.com/doc/refman/8.0/en/replication-options-source.html#sysvar_auto_increment_increment says:
In other words, if you set
auto_increment_increment=2
, this will apply to all tables with an auto-increment column. It is not a per-table option.You could set
auto_increment_increment=2
as a session variable only before inserting into the student table, then set it back to the default before inserting to another table. That sounds like it will be error-prone, because you could forget to change the session variable.