Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - using String as Primary Key

I saw a similar post on Stack Overflow already, but wasn't quite satisfied.

Let's say I offer a Web service. http://foo.com/SERVICEID

SERVICEID is a unique String ID used to reference the service (base 64, lower/uppercase + numbers), similar to how URL shortener services generate ID's for a URL.

I understand that there are inherent performance issues with comparing strings versus integers.

But I am curious of how to maximally optimize a primary key of type String.

I am using MySQL, (currently using MyISAM engine, though I admittedly don't understand all the engine differences).

Thanks.

update for my purpose the string was actually just a base62 encoded integer, so the primary key was an integer, and since you're not likely to ever exceed bigint's size it just doesn't make too much sense to use anything else (for my particular use case)

like image 608
Kenny Cason Avatar asked Aug 11 '10 04:08

Kenny Cason


People also ask

Can we make string as primary key in MySQL?

1 Answer. Yes, from a performance standpoint (i.e. inserting or querying or updating) using Strings for primary keys are slower than integers. But if it makes sense to use string for the primary key then you should probably use it.

Can I use string as primary key?

The short answer : It's perfectly fine to use a string as a primary key.

Can a primary key be text SQL?

You can not set primary key to text and ntext columns. But you can achiveve the same functionality by setting datatype as a varchar(8000). The difference is this column can now contain at most 8000 chars. Ideally you should not use this datatype column as a primary key.

Can we use string as ID?

You can do it, but just because you can, doesn't mean you should.


1 Answers

There's nothing wrong with using a CHAR or VARCHAR as a primary key.

Sure it'll take up a little more space than an INT in many cases, but there are many cases where it is the most logical choice and may even reduce the number of columns you need, improving efficiency, by avoiding the need to have a separate ID field.

For instance, country codes or state abbreviations already have standardised character codes and this would be a good reason to use a character based primary key rather than make up an arbitrary integer ID for each in addition.

like image 175
thomasrutter Avatar answered Sep 23 '22 04:09

thomasrutter