I have a MySQL column that contains phone numbers, the problem is that they're in different formats, such as:
I'd like to know if it's possible to take the existing 10 digits, remove the formatting, and change them all to this format: (212) 555-1212
Not a duplicate, as I'm looking to update several thousand entries instead of masking new entries.
Using CONVERT - SELECT CONVERT( int, 5634.6334) as number. Using ROUND - SELECT ROUND(5634.6334,2) as number. Using CEILING - SELECT FLOOR(5634.6334) as number. Using FLOOR - SELECT CEILING(5634.6334) as number.
E. 164 is an international format which defines a general format for international telephone numbers. Based on this formating, the number contains a country code (CC), a national destination code (NDC), and a subscriber number (SN). There can be up to 15 digits in an E.
Performance : 1. Use CONCAT instead of +; 2. Create a column called Country_ID in both tables and join on that. UI : use FORMAT function to make them look good and you can format them as per their country standards.
I generally use VARCHARs to store telephone numbers. Storage is not so expensive these days that I benefit that much from the savings found by storing them as numeric values.
Unfortunately, no REGEXP_MATCHES()
or TRANSLATE()
function comes with standard MySQL
installation (they do with Postgres
), so you could do this a way which I find really dirty, but it works.
replace()
substr()
concat()
If you have any more characters that you need truncate, just add another replace()
on top of 3 already existing.
Sample data
create table nums ( num text );
insert into nums values
('2125551212'),
('212-555-1212'),
('(212)5551212');
Query formatting your data
select
num,
concat('(',substr(num_cleansed,1,3),') ',substr(num_cleansed,4,3),'-',substr(num_cleansed,7)) AS num_formatted
from (
select
num,
replace(replace(replace(num,'(',''),')',''),'-','') as num_cleansed
from nums
) foo
Result
num num_formatted
2125551212 (212) 555-1212
212-555-1212 (212) 555-1212
(212)5551212 (212) 555-1212
Click here SQLFiddle to preview output.
I'm leaving UPDATE
statement as a homework for the reader.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With