Is it a good idea to use an integer column for storing US ZIP codes in a database?

前端 未结 11 1808
余生分开走
余生分开走 2020-11-29 00:57

From first glance, it would appear I have two basic choices for storing ZIP codes in a database table:

  1. Text (probably most common), i.e. char(5) o
相关标签:
11条回答
  • 2020-11-29 01:14

    Integer is nice, but it only works in the US, which is why most people don't do it. Usually I just use a varchar(20) or so. Probably overkill for any locale.

    0 讨论(0)
  • 2020-11-29 01:17

    Unless you have a business requirement to perform mathematical calculations on ZIP code data, there's no point in using an INT. You're over engineering.

    Hope this helps,

    Bill

    0 讨论(0)
  • 2020-11-29 01:26

    Normally you would use a non-numerical datatype such as a varchar which would allow for more zip code types. If you are dead set on only allowing 5 digit [XXXXX] or 9 digit [XXXXX-XXXX] zip codes, you could then use a char(5) or char(10), but I would not recommend it. Varchar is the safest and most sane choice.

    Edit: It should also be noted that if you don't plan on doing numerical calculations on the field, you should not use a numerical data type. ZIP Code is a not a number in the sense that you add or subtract against it. It is just a string that happens to be made up typically of numbers, so you should refrain from using numerical data types for it.

    0 讨论(0)
  • 2020-11-29 01:27

    If you were to use an integer for US Zips, you would want to multiply the leading part by 10,000 and add the +4. The encoding in the database has nothing to do with input validation. You can always require the input to be valid or not, but the storage is matter of how much you think your requirements or the USPS will change. (Hint: your requirements will change.)

    0 讨论(0)
  • 2020-11-29 01:31

    A numeric ZIP code is -- in a small way -- misleading.

    Numbers should mean something numeric. ZIP codes don't add or subtract or participate in any numeric operations. 12309 - 12345 does not compute the distance from downtown Schenectady to my neighborhood.

    Granted, for ZIP codes, no one is confused. However, for other number-like fields, it can be confusing.

    Since ZIP codes aren't numbers -- they just happen to be coded with a restricted alphabet -- I suggest avoiding a numeric field. The 1-byte saving isn't worth much. And I think that that meaning is more important than the byte.


    Edit.

    "As for leading zeroes..." is my point. Numbers don't have leading zeros. The presence of meaningful leading zeros on ZIP codes is yet another proof that they're not numeric.

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