Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

storing numbers as varchar

Tags:

mysql

Is it ok to store numbers as varchar?

What's the difference between

int 123456789012 and varchar 123456789012 ?

like image 599
Yeti Avatar asked Jun 09 '10 17:06

Yeti


People also ask

Can I store number in VARCHAR?

As the name suggests, varchar means character data that is varying. Also known as Variable Character, it is an indeterminate length string data type. It can hold numbers, letters and special characters.

Can we use VARCHAR for integers?

The VARCHAR data type accepts character strings, including Unicode, of a variable length is up to the maximum length specified in the data type declaration. A VARCHAR declaration must include a positive integer in parentheses to define the maximum allowable character string length.

Can a decimal be a VARCHAR?

3 Answers. The short answer is: No, it will hurt performance. The longer answer: VARCHAR fields are variable length, meaning, that the formatting of the database blocks cannot pre-account for the size of the data filling in there.

Can we use VARCHAR for numeric in SQL?

To convert a varchar type to a numeric type, change the target type as numeric or BIGNUMERIC as shown in the example below: SELECT CAST('344' AS NUMERIC) AS NUMERIC; SELECT CAST('344' AS BIGNUMERIC) AS big_numeric; The queries above should return the specified value converted to numeric and big numeric.


2 Answers

No, it's almost always a bad idea.

  • will use more space
  • indexes will not perform as well
  • you can't do arithmetic
  • the data is not self-validating because of type
  • auto-model generators will give you string type instead of numeric
  • aggregates like SUM will no longer work
  • the output may sort incorrectly
  • you will need to CAST to use it as a number, causing performance hit
  • etc.
like image 96
D'Arcy Rittich Avatar answered Oct 19 '22 07:10

D'Arcy Rittich


You can store leading zeroes to a varchar that you can't do with integer columns (eg. it is possible to have difference between 123 and 0000123). For example zip codes in some countries. However, if you need to do that, then you are really dealing with textual information that should have varchar column. For example, phone numbers or zip codes should definitely go to a varchar column.

Otherwise if you are using your data like numbers (adding them together, comparing them, etc.) then you should put it into integer column. They consume far less space and are faster to use.

like image 20
Juha Syrjälä Avatar answered Oct 19 '22 07:10

Juha Syrjälä