Integer vs String in database

前端 未结 16 593
后悔当初
后悔当初 2020-12-05 13:42

When defining datatypes in a database, I have always had a problem with choosing whether to use integers or strings to store certain \'numerical\' data.

Say I am bui

相关标签:
16条回答
  • 2020-12-05 14:34

    Postcodes are strings. For some comtries, those strings may consist onl of numeric digits, but that doesn't make them integers. And sooner or later your potal system will run out of digits and decide to start using letters as well. If your database uses integers for the postcode field, you will be in deep doo-doo.

    Bottom line - if you don't do arithmetic on it, it's probably not really a number.

    0 讨论(0)
  • 2020-12-05 14:34

    The critical determinant, imho, is whether the applcation will need to do numerical arithmetic calculations on the values, if not, then the only reason to use integers is to reduce the storage requirements, (which "May" be important for performance in a critical application - by reducing the width of a table index to increase index performance, for example) but otherwise, is generally not important...

    If there's no need to do arithmetic with the values, then a string is best.

    0 讨论(0)
  • 2020-12-05 14:39

    In my country, post-codes are also always 4 digits. But the first digit can be zero.

    If you store "0700" as an integer, you can get a lot of problems:

    • It may be read as an octal value
    • If it is read correctly as a decimal value, it gets turned into "700"
    • When you get the value "700", you must remember to add the zero
    • I you don't add the zero, later on, how will you know if "700" is "0700", or someone mistyped "7100"?

    Technically, our post codes is actually strings, even if it is always 4 digits.

    You can store them as integers, to save space. But remember this is a simple DB-trick, and be careful about leading zeroes.

    But what about for storing how many files are in a torrent? Integer or string?

    That's clearly an integer.

    0 讨论(0)
  • 2020-12-05 14:42

    Is '0000' a postcode ? Is it distinct from '0' ?

    If it's always a four-digit number, I would always store it as 4 digits, and that would point to keeping it as a string.

    0 讨论(0)
提交回复
热议问题