Wednesday, 30 August 2017

MySQL column: Change existing phone numbers into specific format?

I have a MySQL column that contains phone numbers, the problem is that they're in different formats, such as:
  • 2125551212
  • 212-555-1212
  • (212)5551212
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.

Solution:
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