Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - how to use VARCHAR as AUTO INCREMENT Primary Key

I am using a VARCHAR as my primary key. I want to auto increment it (base 62, lower/upper case, numbers), However, the below code fails (for obvious reasons):

CREATE TABLE IF NOT EXISTS `campaign` (
  `account_id` BIGINT(20) NOT NULL,
  `type` SMALLINT(5)  NOT NULL,
  `id` VARCHAR(16) NOT NULL AUTO_INCREMENT PRIMARY KEY
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

however, this works:

CREATE TABLE IF NOT EXISTS `campaign` (
  `account_id` BIGINT(20) NOT NULL,
  `type` SMALLINT(5)  NOT NULL,
  `id` VARCHAR(16) NOT NULL PRIMARY KEY
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

What is the best way to keep track of incrementation of 'id' myself? (Since auto_increment doesn't work). Do i need to make another table that contains the current iteration of ID? Or is there a better way to do this?

EDIT: I want to clarify that I know that using INT is a auto_increment primary key is the logical way to go. This question is in response to some previous dialogue I saw. Thanks

like image 903
Kenny Cason Avatar asked Aug 11 '10 05:08

Kenny Cason


People also ask

Can we make varchar as primary key in MySQL?

Of course you can, in the sense that your RDBMS will let you do it. The answer to a question of whether or not you should do it is different, though: in most situations, values that have a meaning outside your database system should not be chosen to be a primary key.

Can we use varchar as primary key?

It is perfectly acceptable to use a varchar column as the primary key. This is often the case when one uses a natural key that doesn't happen to be an integer.

Can varchar be auto increment?

AutoIncrement fields are integer in mysql. You can mirror the auto-increment field in a varchar field and create a trigger which updates the varchar field on insert/update.

Can auto increment be a primary key?

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.


1 Answers

you have to use an INT field
and translate it to whatever format you want at select time

like image 67
Your Common Sense Avatar answered Oct 05 '22 11:10

Your Common Sense