Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use VARCHAR as the PRIMARY KEY?

I have a table for storing coupons/discounts, and I want to use the coupon_code column as the primary key, which is a VARCHAR.

My rationale is that, each coupon will have a unique code, and the only commands I will be running are SELECT ... FROM ... WHERE coupon_code='..'

I won't be doing any joins or indexing, and I don't see there ever being more than a few hundred entries in this table.

It seems to me that this will be OK, but I don't know if there is anything I'm missing/not thinking about.

like image 545
Mike Brady Avatar asked Oct 10 '13 15:10

Mike Brady


People also ask

Does a primary key have to be int?

No, the primary key does not have to be an integer; it's just very common that it is. As an example, we have User ID's here that can have leading zeroes and so must be stored in a varchar field. That field is used as a primary key in our Employee table.

What data type should primary keys be?

Data Type. Integer (number) data types are the best choice for primary key, followed by fixed-length character data types. SQL Server processes number data type values faster than character data type values because it converts characters to ASCII equivalent values before processing, which is an extra step.

What can be used instead of primary key?

Unique identifier (GUID)


1 Answers

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.

If you know that the value is unique in the system that you are modeling, it is appropriate to add a unique index or a unique constraint to your table. However, your primary key should generally be some "meaningless" value, such as an auto-incremented number or a GUID.

The rationale for this is simple: data entry errors and infrequent changes to things that appear non-changeable do happen. They become much harder to fix on values which are used as primary keys.

like image 112
Sergey Kalinichenko Avatar answered Sep 23 '22 10:09

Sergey Kalinichenko