<p>What is a good data structure for storing phone numbers in database fields?  I'm looking for something that is flexible enough to handle international numbers, and also something that allows the various parts of the number to be queried efficiently.</p>

<p><strong>Edit:</strong> Just to clarify the use case here: I currently store numbers in a single varchar field, and I leave them just as the customer entered them.  Then, when the number is needed by code, I normalize it.  The problem is that if I want to query a few million rows to find matching phone numbers, it involves a function, like</p>

<pre><code>where dbo.f_normalizenum(num1) = dbo.f_normalizenum(num2)
</code></pre>

<p>which is terribly inefficient.  Also queries that are looking for things like the area code become extremely tricky when it's just a single varchar field.</p>

<p><strong>[Edit]</strong></p>

<p>People have made lots of good suggestions here, thanks! As an update, here is what I'm doing now: I still store numbers exactly as they were entered, in a varchar field, but instead of normalizing things at query time, I have a trigger that does all that work as records are inserted or updated. So I have ints or bigints for any parts that I need to query, and those fields are indexed to make queries run faster.</p>

[{'answer_id': 41929, 'author': 'Thomas Owens', 'author_id': 572, 'author_profile': 'https://Stackoverflow.com/users/572', 'pm_score': 2, 'selected': False, 'text': '<p>Perhaps storing the phone number sections in different columns, allowing for blank or null entries?</p>\n'}, {'answer_id': 41938, 'author': 'Don', 'author_id': 1989, 'author_profile': 'https://Stackoverflow.com/users/1989', 'pm_score': 1, 'selected': False, 'text': "<p>I think free text (maybe varchar(25)) is the most widely used standard.  This will allow for any format, either domestic or international.</p>\n\n<p>I guess the main driving factor may be how exactly you're querying these numbers and what you're doing with them.</p>\n"}, {'answer_id': 41946, 'author': 'Bjorn Reppen', 'author_id': 1324220, 'author_profile': 'https://Stackoverflow.com/users/1324220', 'pm_score': 6, 'selected': False, 'text': "<p>KISS - I'm getting tired of many of the US web sites.  They have some cleverly written code to validate postal codes and phone numbers.  When I type my perfectly valid Norwegian contact info I find that quite often it gets rejected.</p>\n\n<p>Leave it a string, unless you have some specific need for something more advanced.</p>\n"}, {'answer_id': 41949, 'author': 'ColinYounger', 'author_id': 1223, 'author_profile': 'https://Stackoverflow.com/users/1223', 'pm_score': 1, 'selected': False, 'text': "<p>What about storing a freetext column that shows a user-friendly version of the telephone number, then a normalised version that removes spaces, brackets and expands '+'. For example:</p>\n\n<p><strong>User friendly:</strong> +44 (0)181 4642542</p>\n\n<p><strong>Normalized:</strong> 00441814642542</p>\n"}, {'answer_id': 41955, 'author': 'Aaron', 'author_id': 2628, 'author_profile': 'https://Stackoverflow.com/users/2628', 'pm_score': 1, 'selected': False, 'text': "<p>I find most web forms correctly allow for the country code, area code, then the remaining 7 digits but almost always forget to allow entry of an extension. This almost always ends up making me utter angry words, since at work we don't have a receptionist, and my ext.# is needed to reach me.</p>\n"}, {'answer_id': 41956, 'author': 'Mike Fielden', 'author_id': 4144, 'author_profile': 'https://Stackoverflow.com/users/4144', 'pm_score': 3, 'selected': False, 'text': '<p>I personally like the idea of storing a normalized varchar phone number (e.g. 9991234567) then, of course, formatting that phone number inline as you display it. </p>\n\n<p>This way all the data in your database is "clean" and free of formatting</p>\n'}, {'answer_id': 41964, 'author': 'Thomas Owens', 'author_id': 572, 'author_profile': 'https://Stackoverflow.com/users/572', 'pm_score': 1, 'selected': False, 'text': "<blockquote>\n  <p>I find most web forms correctly allow for the country code, area code, then the remaining 7 digits but almost always forget to allow entry of an extension. This almost always ends up making me utter angry words, since at work we don't have a receptionist, and my ext.# is needed to reach me.</p>\n</blockquote>\n\n<p>I would have to check, but I think our DB schema is similar. We hold a country code (it might default to the US, not sure), area code, 7 digits, and extension.</p>\n"}, {'answer_id': 41982, 'author': 'Adam Davis', 'author_id': 2915, 'author_profile': 'https://Stackoverflow.com/users/2915', 'pm_score': 7, 'selected': True, 'text': "<p>First, beyond the country code, there is no real standard. About the best you can do is recognize, by the country code, which nation a particular phone number belongs to and deal with the rest of the number according to that nation's format.</p>\n\n<p>Generally, however, phone equipment and such is standardized so you can almost always break a given phone number into the following components</p>\n\n<ul>\n<li>C Country code 1-10 digits (right now 4 or less, but that may change)</li>\n<li>A Area code (Province/state/region) code 0-10 digits  (may actually want a region field and an area field separately, rather than one area code)</li>\n<li>E Exchange (prefix, or switch) code 0-10 digits</li>\n<li>L Line number 1-10 digits</li>\n</ul>\n\n<p>With this method you can potentially separate numbers such that you can find, for instance, people that might be close to each other because they have the same country, area, and exchange codes. With cell phones that is no longer something you can count on though.</p>\n\n<p>Further, inside each country there are differing standards. You can always depend on a (AAA) EEE-LLLL in the US, but in another country you may have exchanges in the cities (AAA) EE-LLL, and simply line numbers in the rural areas (AAA) LLLL. You will have to start at the top in a tree of some form, and format them as you have information.  For example, country code 0 has a known format for the rest of the number, but for country code 5432 you might need to examine the area code before you understand the rest of the number.</p>\n\n<p>You may also want to handle <code>vanity</code> numbers such as <code>(800) Lucky-Guy</code>, which requires recognizing that, if it's a US number, there's one too many digits (and you may need to full representation for advertising or other purposes) and that in the US the letters map to the numbers differently than in Germany.</p>\n\n<p>You may also want to store the entire number separately as a text field (with internationalization) so you can go back later and re-parse numbers as things change, or as a backup in case someone submits a bad method to parse a particular country's format and loses information.</p>\n"}, {'answer_id': 42028, 'author': 'jcoby', 'author_id': 2884, 'author_profile': 'https://Stackoverflow.com/users/2884', 'pm_score': 3, 'selected': False, 'text': "<p>Look up E.164.  Basically, you store the phone number as a code starting with the country prefix and an optional pbx suffix.  Display is then a localization issue.  Validation can also be done, but it's also a localization issue (based on the country prefix).</p>\n\n<p>For example, +12125551212+202 would be formatted in the en_US locale as (212) 555-1212 x202.  It would have a different format in <code>en_GB</code> or <code>de_DE</code>.  </p>\n\n<p>There is quite a bit of info out there about ITU-T E.164, but it's pretty cryptic. </p>\n"}, {'answer_id': 46596, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>I would go for a freetext field and a field that contains a purely numeric version of the phone number. I would leave the representation of the phone number to the user and use the normalized field specifically for phone number comparisons in TAPI-based applications or when trying to find double entries in a phone directory. \nOf course it does not hurt providing the user with an entry scheme that adds intelligence like separate fields for country code (if necessary), area code, base number and extension.</p>\n'}, {'answer_id': 170898, 'author': 'cmcculloh', 'author_id': 58, 'author_profile': 'https://Stackoverflow.com/users/58', 'pm_score': 2, 'selected': False, 'text': '<p>Ok, so based on the info on this page, here is a start on an international phone number validator:</p>\n\n<pre><code>function validatePhone(phoneNumber) {\n    var valid = true;\n    var stripped = phoneNumber.replace(/[\\(\\)\\.\\-\\ \\+\\x]/g, \'\');    \n\n    if(phoneNumber == ""){\n        valid = false;\n    }else if (isNaN(parseInt(stripped))) {\n        valid = false;\n    }else if (stripped.length &gt; 40) {\n        valid = false;\n    }\n    return valid;\n}\n</code></pre>\n\n<p>Loosely based on a script from this page: <a href="http://www.webcheatsheet.com/javascript/form_validation.php" rel="nofollow noreferrer">http://www.webcheatsheet.com/javascript/form_validation.php</a></p>\n'}, {'answer_id': 170899, 'author': 'Rich', 'author_id': 22003, 'author_profile': 'https://Stackoverflow.com/users/22003', 'pm_score': 4, 'selected': False, 'text': '<p>The <a href="http://en.wikipedia.org/wiki/E.164" rel="noreferrer">Wikipedia page on E.164</a> should tell you everything you need to know.</p>\n'}, {'answer_id': 170919, 'author': 'Jimoc', 'author_id': 24079, 'author_profile': 'https://Stackoverflow.com/users/24079', 'pm_score': 0, 'selected': False, 'text': "<p>I've used 3 different ways to store phone numbers depending on the usage requirements.</p>\n\n<ol>\n<li>If the number is being stored just for human retrieval and won't be used for searching its stored in a string type field exactly as the user entered it.</li>\n<li>If the field is going to be searched on then any extra characters, such as +, spaces and brackets etc are removed and the remaining number stored in a string type field.</li>\n<li>Finally, if the phone number is going to be used by a computer/phone application, then in this case it would need to be entered and stored as a valid phone number usable by the system, this option of course, being the hardest to code for.</li>\n</ol>\n"}, {'answer_id': 262346, 'author': 'unintentionally left blank', 'author_id': 13231, 'author_profile': 'https://Stackoverflow.com/users/13231', 'pm_score': 3, 'selected': False, 'text': '<p>Here\'s my proposed structure, I\'d appreciate feedback:</p>\n\n<p>The phone database field should be a varchar(42) with the following format:</p>\n\n<p>CountryCode - Number x Extension</p>\n\n<p>So, for example, in the US, we could have:</p>\n\n<p>1-2125551234x1234</p>\n\n<p>This would represent a US number (country code 1) with area-code/number (212) 555 1234 and extension 1234.</p>\n\n<p>Separating out the country code with a dash makes the country code clear to someone who is perusing the data. This is not <em>strictly</em> necessary because country codes are "<a href="http://en.wikipedia.org/wiki/Prefix_code" rel="noreferrer">prefix codes</a>" (you can read them left to right and you will always be able to unambiguously determine the country). But, since country codes have varying lengths (between 1 and 4 characters at the moment) you can\'t easily tell at a glance the country code unless you use some sort of separator. </p>\n\n<p>I use an "x" to separate the extension because otherwise it really wouldn\'t be possible (in many cases) to figure out which was the number and which was the extension.</p>\n\n<p>In this way you can store the entire number, including country code and extension, in a single database field, that you can then use to speed up your queries, instead of joining on a user-defined function as you have been painfully doing so far.</p>\n\n<p>Why did I pick a varchar(42)? Well, first off, international phone numbers will be of varied lengths, hence the "var". I am storing a dash and an "x", so that explains the "char", and anyway, you won\'t be doing integer arithmetic on the phone numbers (I guess) so it makes little sense to try to use a numeric type. As for the length of 42, I used the maximum possible length of all the fields added up, based on Adam Davis\' answer, and added 2 for the dash and the \'x". </p>\n'}, {'answer_id': 262382, 'author': 'Mark Baker', 'author_id': 11815, 'author_profile': 'https://Stackoverflow.com/users/11815', 'pm_score': 0, 'selected': False, 'text': "<p>Where are you getting the phone numbers from? If you're getting them from part of the phone network, you'll get a string of digits and a number type and plan, eg</p>\n\n<p>441234567890 type/plan 0x11 (which means international E.164)</p>\n\n<p>In most cases the best thing to do is to store all of these as they are, and normalise for display, though storing normalised numbers can be useful if you want to use them as a unique key or similar. </p>\n"}, {'answer_id': 7567049, 'author': 'dave singer', 'author_id': 966509, 'author_profile': 'https://Stackoverflow.com/users/966509', 'pm_score': 0, 'selected': False, 'text': '<blockquote>\n  <p>User friendly: +44 (0)181 464 2542 normalised: 00441814642542</p>\n</blockquote>\n\n<p>The (0) is not valid in the international format. See the ITU-T E.123 standard.</p>\n\n<p>The "normalised" format would not be useful to US readers as they use 011 for international access.</p>\n'}, {'answer_id': 42857695, 'author': 'Brian West', 'author_id': 1260514, 'author_profile': 'https://Stackoverflow.com/users/1260514', 'pm_score': 2, 'selected': False, 'text': '<p>The standard for formatting numbers is <a href="https://en.wikipedia.org/wiki/E.164" rel="nofollow noreferrer">e.164</a>, You should always store numbers in this format.  You should never allow the extension number in the same field with the phone number, those should be stored separately.  As for numeric vs alphanumeric, It depends on what you\'re going to be doing with that data.</p>\n'}, {'answer_id': 51761170, 'author': 'Alex Klaus', 'author_id': 968003, 'author_profile': 'https://Stackoverflow.com/users/968003', 'pm_score': 3, 'selected': False, 'text': '<p><strong>Storage</strong></p>\n<p>Store phones in <a href="https://www.ietf.org/rfc/rfc3966.txt" rel="nofollow noreferrer">RFC 3966</a> (like <code>+1-202-555-0252</code>, <code>+1-202-555-7166;ext=22</code>). The main differences from <a href="https://en.wikipedia.org/wiki/E.164" rel="nofollow noreferrer">E.164</a> are</p>\n<ul>\n<li>No limit on the length</li>\n<li>Support of extensions</li>\n</ul>\n<p>To optimise speed of fetching the data, also store the phone number in the National/International format, in addition to the RFC 3966 field.</p>\n<p>Don\'t store the country code in a separate field unless you have a serious reason for that. Why? Because you shouldn\'t ask for the country code on the UI.</p>\n<p>Mostly, people enter the phones as they hear them. E.g. if the local format starts with <code>0</code> or <code>8</code>, it\'d be annoying for the user to do a transformation on the fly (like, &quot;<em>OK, don\'t type \'0\', choose the country and type the rest of what the person said in this field</em>&quot;).</p>\n<p><strong>Parsing</strong></p>\n<p>Google has your back here. Their <a href="https://github.com/googlei18n/libphonenumber" rel="nofollow noreferrer">libphonenumber</a> library can validate and parse any phone number. There are ports to almost any language.</p>\n<p>So let the user just enter &quot;<code>0449053501</code>&quot; or &quot;<code>04 4905 3501</code>&quot; or &quot;<code>(04) 4905 3501</code>&quot;. The tool will figure out the rest for you.</p>\n<p>See the <a href="https://rawgit.com/googlei18n/libphonenumber/master/javascript/i18n/phonenumbers/demo-compiled.html" rel="nofollow noreferrer">official demo</a>, to get a feeling of how much does it help.</p>\n'}]
['https://Stackoverflow.com/questions/41925', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1219/']