user1432124
user1432124

Reputation:

Int id vs. varchar id

Which type of id is better for querying and to use as foreign key in mysql:

1)Varchar id with size 20

2)Int id

Upvotes: 8

Views: 13390

Answers (3)

poy
poy

Reputation: 10507

Int IDS are more efficient because the database will only have to compare once.

So lets say you have n rows. If you use an int then you're looking at O(n) as a worst case. Where as if you use a varchar(20) you're looking at O(n*20)

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838216

An int is usually better, because it gives better performance.

If your item has a natural key which is a varchar, you could use that and it will work. But you will get a performance improvement (and some other benefits) by adding a surrogate key that is an integer. You can add an AUTO_INCREMENT column for this purpose.

Upvotes: 12

Schalk
Schalk

Reputation: 142

INT IDs are always preferable..

It is faster and uses less storage on the database.

There are cases when VARCHAR IDs are needed, but INT is more efficient

Upvotes: 0

Related Questions