Mask names in query results
Build the masked value in the SELECT list with string functions: first letter kept, the remainder replaced by asterisks.
The task
Support staff need to see who a record is without reading full names. Masking in the query means the stored data stays intact and only the exposed view changes.
The snippet
Written for PostgreSQL. Versions for SQL Server are under Variations.
SELECT id,
LEFT(TRIM(name), 1) || REPEAT('*', GREATEST(LENGTH(TRIM(name)) - 1, 0)) AS masked_name
FROM customers
WHERE name IS NOT NULL
ORDER BY id;
工作原理
LEFT(name, 1) keeps the initial; REPEAT('*', length - 1) builds a mask for the rest, and GREATEST(..., 0) stops an empty name from asking for a negative repeat count. The same expression works on MySQL with CONCAT in place of || and CHAR_LENGTH in place of LENGTH, because MySQL's LENGTH counts bytes and would over-mask accented names. In the SQL Server variant, REPLICATE with a negative count returns NULL, so an empty name comes back as NULL rather than an empty mask. Because the mask is built at read time, nothing is destroyed; run the same query without the expression to see real names when you have the rights to.
Variations
SQL Server: LEFT + REPLICATE
SQL ServerSELECT id,
LEFT(TRIM(name), 1) + REPLICATE('*', LEN(TRIM(name)) - 1) AS masked_name
FROM customers
WHERE name IS NOT NULL;
Mask everything but the last two characters
SELECT id,
REPEAT('*', GREATEST(LENGTH(TRIM(name)) - 2, 0))
|| RIGHT(TRIM(name), 2) AS masked_name
FROM customers
WHERE name IS NOT NULL;
Questions that come up
Is SELECT-time masking enough for privacy?
It is exactly the right tool when viewers may see presence but not content, because the source of truth never changes and no cleanup job can leak. It is not enough for copies that leave the database: exports, logs and backups still carry the real values, and those need true anonymization (the anonymize-emails recipe) or access control at the copy step.
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.