← Back to SQL, page 8

sql-0144 · Easy fresher

Write a query that normalizes phone numbers by removing spaces, dashes and brackets.

Nest REPLACE calls, one per unwanted character: REPLACE(REPLACE(REPLACE(REPLACE(phone, ' ', ''), '-', ''), '(', ''), ')', ''). PostgreSQL can do it in one call with REGEXP_REPLACE(phone, '[^0-9+]', '', 'g'). Store the cleaned form, and keep formatting for display.

Full answer
sql
CREATE TABLE contacts (
  id    INTEGER PRIMARY KEY,
  first TEXT,
  last  TEXT,
  email TEXT,
  phone TEXT
);
INSERT INTO contacts VALUES
  (1,'Asha','Rao','asha.rao@example.com','+91 98450-12345'),
  (2,'ben',NULL,'Ben@Mail.example.org','(020) 7946 0018'),
  (3,'  Chen ','Li','chen_li@example.com','020-7946-0019'),
  (4,'Dara','Okafor',NULL,'12345');
sql
SELECT id, phone,
       REPLACE(REPLACE(REPLACE(REPLACE(phone, ' ', ''), '-', ''), '(', ''), ')', '') AS clean
FROM contacts ORDER BY id;
idphoneclean
1+91 98450-12345+919845012345
2(020) 7946 001802079460018
3020-7946-001902079460019
41234512345

Each REPLACE removes one character everywhere it occurs. Four nested calls handle spaces, dashes and both brackets. The leading + stays, because the country code matters.

PostgreSQL's regular-expression version keeps only digits and +:

sql
SELECT id, REGEXP_REPLACE(phone, '[^0-9+]', '', 'g') AS clean FROM contacts ORDER BY id;
idclean
1+919845012345
202079460018
302079460019
412345

SQLite has no built-in REGEXP_REPLACE; the REGEXP operator exists only if an application or extension defines it. For anything beyond a few characters, clean in application code before insert.

sql
CREATE TABLE contacts (
  id    INTEGER PRIMARY KEY,
  first TEXT,
  last  TEXT,
  email TEXT,
  phone TEXT
);
INSERT INTO contacts VALUES
  (1,'Asha','Rao','asha.rao@example.com','+91 98450-12345'),
  (2,'ben',NULL,'Ben@Mail.example.org','(020) 7946 0018'),
  (3,'  Chen ','Li','chen_li@example.com','020-7946-0019'),
  (4,'Dara','Okafor',NULL,'12345');

SELECT id, phone,
       REPLACE(REPLACE(REPLACE(REPLACE(phone, ' ', ''), '-', ''), '(', ''), ')', '') AS clean
FROM contacts ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • REPLACE(s, from, to) replaces every occurrence
  • Nest REPLACE calls for several characters
  • PostgreSQL has REGEXP_REPLACE with the 'g' flag
  • Store a normalized form; format on display

Common mistakes

  • Removing the + and losing the country code
  • Forgetting the 'g' flag and replacing only the first match in PostgreSQL

Follow-ups

  • How would you find duplicate contacts by normalized phone?
  • Where should phone validation live?

Tips

  • Mention storing E.164 format as a design choice