// SQL snippet

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.

Main statement
PostgreSQL
Couvre également
SQL Server MySQL Oracle

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.

PostgreSQL
SELECT repeat('*', GREATEST(length(card_no) - 4, 0)) || right(card_no, 4) AS card_masked
FROM payment_methods;

Fonctionnement

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 Server
SELECT 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)

Oracle
SELECT 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

MySQL
SELECT 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

// snippets are better with a schema brain

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.