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;| id | phone | clean |
|---|---|---|
| 1 | +91 98450-12345 | +919845012345 |
| 2 | (020) 7946 0018 | 02079460018 |
| 3 | 020-7946-0019 | 02079460019 |
| 4 | 12345 | 12345 |
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;| id | clean |
|---|---|
| 1 | +919845012345 |
| 2 | 02079460018 |
| 3 | 02079460019 |
| 4 | 12345 |
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