SQL string masking
Turn sensitive values into display-safe form: ****1234. The pattern is length math plus repeat; the gotchas are lengths on multibyte and where the mask runs.
- 類別
- Strings
- Returns
string- In this category
- 73 of 172
語法
REPLICATE('*', LEN(s) - 4) + RIGHT(s, 4)
引擎支援
| 引擎 | Support | 備註 |
|---|---|---|
| SQL Server | 是 | Supported under this name. |
| PostgreSQL | 是 | Supported under this name. |
| MySQL | 是 | Supported under this name. |
| SQLite | 是 | Supported under this name. |
| Oracle | 是 | Supported under this name. |
範例
SQL Server
SELECT REPLICATE('*', LEN(number) - 4) + RIGHT(number, 4) AS masked FROM cards;
-- ************3456
PostgreSQL
SELECT CONCAT(REPEAT('*', GREATEST(length(email) - 3, 0)), right(email, 3)) AS masked FROM users;
Oracle
SELECT RPAD('*', LENGTH(card) - 4, '*') || SUBSTR(card, -4) AS masked FROM cards;
小知識
- The recipe: star everything but the tail. SQL Server REPLICATE('*', LEN(s) - 4) + RIGHT(s, 4); PostgreSQL REPEAT and RIGHT; Oracle RPAD('*', LENGTH(s) - 4, '*') || SUBSTR(s, -4).
- Guard short values: LEN(s) - 4 goes negative under 4 characters, and SQL Server's REPLICATE returns NULL for negative counts.
- Width math assumes one unit per character: SQL Server's LEN counts an emoji as 2 under non-SC collations, and MySQL's LENGTH counts bytes. Use CHAR_LENGTH on MySQL and an _SC collation on SQL Server when the data can hold them.
- Masks in reports are cosmetic: SQL Server's dynamic data masking and view-based masking protect display, not access; users with query rights can often derive the value.
Questions about Masking strings
Why did my mask return NULL?
A negative repeat count: values shorter than the keep-length make LEN(s) - 4 negative, and SQL Server's REPLICATE returns NULL. Clamp with IIF/GREATEST.
Is SQL Server's dynamic data masking secure?
It hides values from unmasked users' results but is not a security boundary; users can often infer values through queries. Real protection is permissions and encryption.
Should I mask stored data or at query time?
Store the real value, mask in views or at read time; masking on write destroys the data. Only hashed or tokenized replacements should ever be stored in place.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.