Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a primary key start with a specific letter?

Tags:

java

mysql

swing

Here I am using MySQL and I want my primary key to start with a letter, like D000. Then everytime I enter a new record the primary key auto increments like so:

D001 D002 D003.

How can I do this?

like image 249
Kogile Avatar asked Sep 10 '14 10:09

Kogile


People also ask

How do I change primary key from beginning to one?

alter table yourTableName AUTO_INCREMENT=1; truncate table yourTableName; After doing the above two steps, you will get the primary key beginning from 1.

Can a primary key be a name?

Thus, all Candidate Keys are Unique Keys. A Primary Key is simply the designation of one of the Candidate Keys as the preferred way to access table data. In light of this, the name PRIMARY KEY is the arbitrary name of the preferred candidate key attached as a table property. There can only be one Primary Key.

Can there be 2 primary key?

A primary key is a field or set of fields with values that are unique throughout a table. Values of the key can be used to refer to entire records, because each record has a different value for the key. Each table can only have one primary key.

Can there be 3 primary keys?

A primary key is used as a unique identifier to quickly parse data within the table. A table cannot have more than one primary key. A primary key's main features are: It must contain a unique value for each row of data.


1 Answers

You can't AUTO_INCREMENT a column whose type is VARCHAR.

What you could do is make it BIGINT and AUTO_INCREMENT, and whenever you need it as String, you can prepend it with your letter 'D' like:

Long dbKey = ...;
String key = "D" + dbKey;

You could create a stored procedure for this to set an "auto-incremented" string as the default value for this column, but it just doesn't worth the hassle. Plus working with numbers is always faster and more efficient than working with strings.

like image 164
icza Avatar answered Nov 04 '22 15:11

icza