Mask payment card numbers in SQL (show last 4)
Support screens and exports must never show a full card number. Keep the last four for identification.
The task
Show agents enough of the card to identify it. Everything before the last four digits becomes asterisks.
The snippet
Written for PostgreSQL. Versions for SQL Server, MySQL and Oracle are under Variations.
SELECT repeat('*', GREATEST(length(card_no) - 4, 0)) || right(card_no, 4) AS card_masked
FROM payment_methods;
仕組み
right(card_no, 4) keeps the final four characters, repeat('*') pads the remainder to the original length, and GREATEST guards very short values from a negative repeat count. The result is a string, so the masked column is for display only and never round-trips.
Variations
SQL Server
SQL ServerSELECT REPLICATE('*', IIF(LEN(card_no) > 4, LEN(card_no) - 4, 0)) + RIGHT(card_no, 4) AS card_masked
FROM payment_methods;
Oracle (SUBSTR(x, -4) is NULL when x is shorter than 4)
OracleSELECT CASE WHEN LENGTH(card_no) > 4
THEN LPAD(SUBSTR(card_no, -4), LENGTH(card_no), '*')
ELSE card_no END AS card_masked
FROM payment_methods;
MySQL
MySQLSELECT CONCAT(REPEAT('*', GREATEST(LENGTH(card_no) - 4, 0)), RIGHT(card_no, 4)) AS card_masked
FROM payment_methods;
Questions that come up
Is masking enough to make data safe?
No. Masking is display-only. If the underlying column should not be readable at all, store only a hash or a token, or encrypt and control keys. Masking in the query does nothing when someone can read the table directly.
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.