Anonymize email addresses in SQL
Build a fake-but-unique address from the row id so references stay stable, and UPDATE only rows that currently hold a real-looking email.
The task
A production copy is heading to a staging environment and every customer email must go. A deterministic placeholder keeps joins and uniqueness working while removing the personal data.
The snippet
Written for PostgreSQL. Versions for SQL Server and MySQL are under Variations.
BEGIN;
UPDATE customers
SET email = 'user' || id || '@example.invalid'
WHERE email LIKE '%_@_%';
-- check the row count, then COMMIT; or ROLLBACK;
How it works
The new value concatenates the row's id into a placeholder at the reserved example.invalid domain, so every anonymized address stays unique and clearly fake. The WHERE limits the write to rows that hold an email-shaped value (LIKE is never true for NULL, so NULLs stay NULL); rows with junk that is not email-shaped keep it, so check them with validate-email-shape before the copy leaves. The UPDATE runs unchanged on Oracle, SQLite and SQL Server 2025; MySQL treats || as OR by default and older SQL Server has no || at all, so use CONCAT there. The transaction matters because this UPDATE is deliberately destructive: there is no going back to the original addresses from the database alone.
Variations
Keep the domain, mask the local part
UPDATE customers
SET email = 'user' || id || '@' || split_part(email, '@', 2)
WHERE email LIKE '%_@_%';
MySQL and SQL Server: CONCAT instead of ||
SQL Server MySQLUPDATE customers
SET email = CONCAT('user', id, '@example.invalid')
WHERE email IS NOT NULL
AND email LIKE '%_@_%';
Questions that come up
Why example.invalid and not example.com?
The .invalid top-level domain is reserved (RFC 2606) for names that must never resolve, so any mail sent to an anonymized address fails at DNS lookup. example.com is reserved too, but for documentation, and it is a real, resolving domain: mail to it is refused only because its operator publishes a null MX record. A name that cannot resolve at all is the safer placeholder.
Keep reading
Related on SQLly
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.