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

前端 未结 11 1869
余生分开走
余生分开走 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:07

    Use a string with validation. Zip codes can begin with 0, so numeric is not a suitable type. Also, this applies neatly to international postal codes (e.g. UK, which is up to 8 characters). In the unlikely case that postal codes are a bottleneck, you could limit it to 10 characters, but check out your target formats first.

    Here are validation regexes for UK, US and Canada.


    Yes, you can pad to get the leading zeroes back. However, you're theoretically throwing away information that might help in case of errors. If someone finds 1235 in the database, is that originally 01235, or has another digit been missed?

    Best practice says you should say what you mean. A zip code is a code, not a number. Are you going to add/subtract/multiply/divide zip codes? And from a practical perspective, it's far more important that you're excluding extended zips.

提交回复
热议问题