Example 1
Mask phone numbers in a message column
The pattern [0-9]{3}-[0-9]{3}-[0-9]{4} matches three digits, a hyphen, three digits, a hyphen, and four digits — the standard North American phone format. Both occurrences in the string are replaced with the literal mask. MySQL/MariaDB replace all matches automatically; PostgreSQL requires the 'g' (global) flag to replace all rather than just the first match.
CREATE TABLE messages (id INT, body VARCHAR(200));
INSERT INTO
messages
VALUES
(1, 'Call 555-123-4567 or 555-987-6543 for info');SELECT
id,
REGEXP_REPLACE (
body,
'[0-9]{3}-[0-9]{3}-[0-9]{4}',
'XXX-XXX-XXXX'
) AS masked
FROM
messages
ORDER BY
id;| id | masked |
|---|---|
| 1 | Call XXX-XXX-XXXX or XXX-XXX-XXXX for info |
CREATE TABLE messages (id INT, body VARCHAR(200));
INSERT INTO
messages
VALUES
(1, 'Call 555-123-4567 or 555-987-6543 for info');SELECT
id,
REGEXP_REPLACE (
body,
'[0-9]{3}-[0-9]{3}-[0-9]{4}',
'XXX-XXX-XXXX',
'g'
) AS masked
FROM
messages
ORDER BY
id;| id | masked |
|---|---|
| 1 | Call XXX-XXX-XXXX or XXX-XXX-XXXX for info |
PostgreSQL requires the 'g' flag to replace all occurrences. MySQL and MariaDB replace all matches by default. SQL Server and SQLite do not support REGEXP_REPLACE.