Skip to Main Content
Linking to Interactive Reports Modal Dialog

Mask Digits

How to mask a string 123-45-6789 and only show the last 4 digits.

Example:

DECLARE
    input_str VARCHAR2(20) := '123-45-6789';
    masked_str VARCHAR2(20);
    temp_str VARCHAR2(20);
BEGIN
    -- Remove dashes
    temp_str := REGEXP_REPLACE(input_str, '-', '');
    
    -- Mask digits except last 4
    temp_str := LPAD(SUBSTR(temp_str, -4), LENGTH(temp_str), '*');
    
    -- Re-add dashes
    masked_str := SUBSTR(temp_str, 1, 3) || '-' || SUBSTR(temp_str, 4, 2) || '-' || SUBSTR(temp_str, 6);
    
    DBMS_OUTPUT.PUT_LINE(masked_str);
END;
/

Or

SELECT
    SUBSTR( LPAD(SUBSTR( REGEXP_REPLACE( COLUMN_NAME , '-', ''), -4), LENGTH( REGEXP_REPLACE( COLUMN_NAME , '-', '')), '*'), 1, 3) || '-' || 
    SUBSTR( LPAD(SUBSTR( REGEXP_REPLACE( COLUMN_NAME , '-', ''), -4), LENGTH( REGEXP_REPLACE( COLUMN_NAME , '-', '')), '*'), 4, 2) || '-' || 
    SUBSTR( LPAD(SUBSTR( REGEXP_REPLACE( COLUMN_NAME , '-', ''), -4), LENGTH( REGEXP_REPLACE( COLUMN_NAME , '-', '')), '*'), 6) 
    AS MASK_COLUMN_NAME
FROM DUAL