Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set initial value and auto increment in MySQL?

How do I set the initial value for an "id" column in a MySQL table that start from 1001?

I want to do an insert "INSERT INTO users (name, email) VALUES ('{$name}', '{$email}')";

Without specifying the initial value for the id column.

like image 200
bbtang Avatar asked Sep 28 '09 06:09

bbtang


People also ask

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.

What is AUTO_INCREMENT in MySQL?

Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.

Does MySQL primary key auto increment?

One of the important tasks while creating a table is setting the Primary Key. The Auto Increment feature allows you to set the MySQL Auto Increment Primary Key field. This automatically generates a sequence of unique numbers whenever a new row of data is inserted into the table.


2 Answers

Use this:

ALTER TABLE users AUTO_INCREMENT=1001; 

or if you haven't already added an id column, also add it

ALTER TABLE users ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT,     ADD INDEX (id); 
like image 70
Anatoliy Avatar answered Oct 14 '22 04:10

Anatoliy


MySQL - Setup an auto-incrementing primary key that starts at 1001:

Step 1, create your table:

create table penguins(   my_id       int(16) auto_increment,    skipper     varchar(4000),   PRIMARY KEY (my_id) ) 

Step 2, set the start number for auto increment primary key:

ALTER TABLE penguins AUTO_INCREMENT=1001; 

Step 3, insert some rows:

insert into penguins (skipper) values("We need more power!"); insert into penguins (skipper) values("Time to fire up"); insert into penguins (skipper) values("kowalski's nuclear reactor."); 

Step 4, interpret the output:

select * from penguins 

prints:

'1001', 'We need more power!' '1002', 'Time to fire up' '1003', 'kowalski\'s nuclear reactor' 
like image 45
Eric Leschinski Avatar answered Oct 14 '22 04:10

Eric Leschinski