Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Database auto-increment column

Tags:

sql

Is it possible to create a Database which has 1 column (but not the column of primary key) to be auto-increment? So that when I insert value to the database, i don't need to fill in the value myself, and DB will fill in that value for that column for me (and increment every time I do a new insert)?

Thank you.

like image 965
lucius Avatar asked Apr 21 '26 18:04

lucius


1 Answers

Yes, of course it is possible. Just make this column a unique key (not a primary key) and it has to be declared with a special attribute: "IDENTITY" for SQL Server, and "AUTO_INCREMENT" for MySQL (see the example below) . And another column can be a primary key.

On MySQL database the table could be declared like this:

CREATE TABLE `mytable` (
  `Name` VARCHAR(50) NOT NULL,
  `My_autoincrement_column` INTEGER(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`Name`),
  UNIQUE KEY `My_autoincrement_column` (`My_autoincrement_column`)
);
like image 137
nightcoder Avatar answered Apr 24 '26 07:04

nightcoder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!