Mask an email address in SQL for display
Privacy rules often let you show the first letter and domain but not the full local part.
The task
Show the first letter and the domain, hide the rest of the local part with asterisks.
The snippet
Written for PostgreSQL. Versions for SQL Server and MySQL are under Variations.
SELECT left(email, 1) || '***@' || split_part(email, '@', 2) AS email_masked
FROM users;
仕組み
left(email, 1) keeps the first character of the local part, and split_part recovers the domain after the @. Concatenating the fixed '***@' between them yields a display form that cannot be reversed to the original address, as long as the local part had more than one character.
Variations
SQL Server
SQL ServerSELECT LEFT(email, 1) + '***@' + RIGHT(email, CHARINDEX('@', REVERSE(email) + '@') - 1) AS email_masked
FROM users;
MySQL
MySQLSELECT CONCAT(LEFT(email, 1), '***@', SUBSTRING_INDEX(email, '@', -1)) AS email_masked
FROM users;
Questions that come up
Should the mask length match the real local part?
Some policies prefer a fixed-width mask so the mask itself leaks nothing about length. If that matters to you, emit a constant '***' (as here) rather than one star per hidden character.
Keep reading
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.