Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawbacks of storing an integer as a string in a database

Tags:

I have id values for products that I need store. Right now they are all integers, but I'm not sure if the data provider in the future will introduce letters or symbols into that mix, so I'm debating whether to store it now as integer or string.

Are there performance or other disadvantages to saving the values as strings?

like image 558
rick Avatar asked Jul 07 '09 01:07

rick


People also ask

Should primary key be integer or string?

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 numbers be stored in a string?

A string consists of one or more characters, which can include letters, numbers, and other types of characters. You can think of a string as plain text.

Do strings or integers take up more space?

strings take up more memory, but the memory size is tiny... an integer takes up about 4 bytes for its actual data (some extra for memory pointers depending on how you store it, but string will have that same extra memory as well). A string takes up about a byte per letter (with a minimum of course as .


1 Answers

Unless you really need the features of an integer (that is, the ability to do arithmetic), then it is probably better for you to store the product IDs as strings. You will never need to do anything like add two product IDs together, or compute the average of a group of product IDs, so there is no need for an actual numeric type.

It is unlikely that storing product IDs as strings will cause a measurable difference in performance. While there will be a slight increase in storage size, the size of a product ID string is likely to be much smaller than the data in the rest of your database row anyway.

Storing product IDs as strings today will save you much pain in the future if the data provider decides to start using alphabetic or symbol characters. There is no real downside.

like image 184
Greg Hewgill Avatar answered Oct 03 '22 19:10

Greg Hewgill