Data Masking, Subsetting and Data Redaction in Oracle Database 23ai — Command-Line Runbook
Updated: Oct 24
Environment used in this runbook:
Production PDB: PROD_PDB (Oracle Database 23ai, CDB CDB23)
Staging clone: STAGE_PDB, used for masking and subsetting
Developer PDB: DEV_PDB
Demo schema: SALES (CUSTOMERS, ORDERS, ORDER_ITEMS, EMPLOYEES)
Security administrator: SEC_ADMIN
Tools: SQL*Plus, PL/SQL and Data Pump only (no Enterprise Manager, no Data Safe)
Three techniques, one problem
Technique | What it changes | Where | Typical use |
Data Redaction (dynamic) | Nothing on disk; values are masked in the result set of a query, per session | Production | Call-centre screens, reports, third-party tools |
Static masking | Data is permanently replaced by realistic fake values | A copy of production | Dev, test, training, analytics |
Subsetting | A referentially consistent fraction of the rows is kept | A copy, or during export | Smaller test databases, faster refreshes |
How to pick: if the person should not see the value in production, redact. If the data leaves production (a clone, a dump, a laptop), mask — redaction does not protect a copy once someone with the right privilege reads it. Subsetting is about volume, not secrecy, and almost always travels with masking.
Two rules that hold throughout: never mask production in place (clone first), and treat every dump file, staging clone and masking script as sensitive until the result is verified.
Licensing reminder: Data Redaction is part of Oracle Advanced Security on-premises (included on OCI and in 23ai Free); Data Pump REMAP_DATA, QUERY and SAMPLE, PL/SQL and PDB cloning are core database features. Check your contract before you go live.
Part 0 — Groundwork shared by all three techniques
Step 0.1 — Demo schema and administrators
SQL |
ALTER SESSION SET CONTAINER = prod_pdb;
CREATE USER sec_admin IDENTIFIED BY "SecAdmin#2026"; GRANT CREATE SESSION, CREATE TABLE, CREATE PROCEDURE, CREATE JOB, UNLIMITED TABLESPACE TO sec_admin; GRANT EXECUTE ON dbms_redact TO sec_admin; -- redaction policies GRANT EXECUTE ON dbms_crypto TO sec_admin; -- keyed hashes inside the masking functions GRANT SELECT_CATALOG_ROLE TO sec_admin; -- discovery queries on DBA_* views
CREATE USER app_user IDENTIFIED BY "App#2026"; CREATE USER cc_agent IDENTIFIED BY "Agent#2026"; GRANT CREATE SESSION TO app_user, cc_agent;
CREATE USER etl_user IDENTIFIED BY "Etl#2026"; -- runs Data Pump; exempted from redaction in Step 1.6 GRANT CREATE SESSION, DATAPUMP_EXP_FULL_DATABASE, DATAPUMP_IMP_FULL_DATABASE TO etl_user;
CREATE TABLE sales.customers ( cust_id NUMBER PRIMARY KEY, full_name VARCHAR2(60), email VARCHAR2(80) CONSTRAINT customers_email_uk UNIQUE, card_number VARCHAR2(19), national_id VARCHAR2(11), birth_date DATE, country VARCHAR2(2), balance NUMBER(12,2), vip BOOLEAN);
CREATE TABLE sales.orders ( order_id NUMBER PRIMARY KEY, cust_id NUMBER NOT NULL CONSTRAINT orders_cust_fk REFERENCES sales.customers, order_date DATE, amount NUMBER(12,2));
CREATE TABLE sales.order_items ( item_id NUMBER PRIMARY KEY, order_id NUMBER NOT NULL CONSTRAINT order_items_order_fk REFERENCES sales.orders, product VARCHAR2(40), qty NUMBER);
CREATE TABLE sales.employees ( emp_id NUMBER PRIMARY KEY, full_name VARCHAR2(60), email VARCHAR2(80), salary NUMBER(10,2));
INSERT INTO sales.customers VALUES (1,'John Doe','john.doe@acme.com','4532-1111-2222-3456','123-45-6789',DATE '1985-03-14','DE',15230.50,TRUE); INSERT INTO sales.customers VALUES (2,'Jane Roe','jane.roe@acme.com','5100-9999-8888-7777','987-65-4321',DATE '1990-11-02','FR', 420.00,FALSE); INSERT INTO sales.orders VALUES (10,1,DATE '2026-01-15',199.90); INSERT INTO sales.orders VALUES (11,2,DATE '2026-02-03', 59.00); INSERT INTO sales.order_items VALUES (100,10,'Keyboard',2); INSERT INTO sales.order_items VALUES (101,11,'Mouse',1); INSERT INTO sales.employees VALUES (7,'Max Muster','max.muster@acme.com',82000); COMMIT;
GRANT SELECT ON sales.customers TO app_user, cc_agent, sec_admin; |
Why: SEC_ADMIN owns the policies and the masking code but no application data — separating the two is what auditors expect. DBMS_CRYPTO is used instead of STANDARD_HASH because it is callable from PL/SQL without a context switch to SQL. CREATE JOB is needed later for parallel masking with DBMS_PARALLEL_EXECUTE.
Step 0.2 — Find the sensitive columns (no discovery tool needed)
SQL |
-- 1) by name and comment SELECT c.owner, c.table_name, c.column_name, c.data_type, cc.comments FROM dba_tab_columns c JOIN dba_tables t ON t.owner = c.owner AND t.table_name = c.table_name LEFT JOIN dba_col_comments cc ON cc.owner = c.owner AND cc.table_name = c.table_name AND cc.column_name = c.column_name WHERE c.owner = 'SALES' AND ( REGEXP_LIKE(c.column_name, 'SSN|NATIONAL|PASSPORT|CARD|CCN|PAN|IBAN|EMAIL|PHONE|BIRTH|DOB|SALARY|ADDRESS|NAME', 'i') OR REGEXP_LIKE(cc.comments, 'personal|sensitive|PII|GDPR', 'i') ) ORDER BY 1, 2, 3;
-- 2) by content: sample every text column of the schema for e-mail and card-number patterns SET SERVEROUTPUT ON DECLARE l_cnt NUMBER; TYPE t_pat IS TABLE OF VARCHAR2(200) INDEX BY VARCHAR2(20); l_pat t_pat; BEGIN l_pat('EMAIL') := '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$'; l_pat('CARD') := '^[0-9]{4}[ -]?[0-9]{4}[ -]?[0-9]{4}[ -]?[0-9]{4}$'; l_pat('US_SSN') := '^[0-9]{3}-[0-9]{2}-[0-9]{4}$'; FOR c IN (SELECT c.owner, c.table_name, c.column_name FROM dba_tab_columns c JOIN dba_tables t ON t.owner = c.owner AND t.table_name = c.table_name WHERE c.owner = 'SALES' AND c.data_type IN ('VARCHAR2','CHAR','NVARCHAR2')) LOOP FOR p IN (SELECT 'EMAIL' k FROM dual UNION ALL SELECT 'CARD' FROM dual UNION ALL SELECT 'US_SSN' FROM dual) LOOP EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM "'||c.owner||'"."'||c.table_name||'" SAMPLE(10) WHERE REGEXP_LIKE("'||c.column_name||'", :1)' INTO l_cnt USING l_pat(p.k); IF l_cnt > 0 THEN DBMS_OUTPUT.PUT_LINE(c.table_name||'.'||c.column_name||' looks like '||p.k||' ('||l_cnt||' hits in a 10% sample)'); END IF; END LOOP; END LOOP; END; / |
Record what you found — this table drives both the production policies and the non-production masking, and it is the evidence you hand to auditors:
SQL |
CREATE TABLE sec_admin.sensitive_columns ( owner VARCHAR2(128), table_name VARCHAR2(128), column_name VARCHAR2(128), category VARCHAR2(30), -- EMAIL, CARD, NATIONAL_ID, NAME, DOB, FINANCIAL ... prod_control VARCHAR2(40), -- how production protects it: REDACT:FULL, REDACT:PARTIAL, VPD, none nonprod_mask VARCHAR2(80)); -- which masking function the clone gets
INSERT INTO sec_admin.sensitive_columns VALUES ('SALES','CUSTOMERS','FULL_NAME', 'NAME', 'none', 'mask_pkg.mask_name'); INSERT INTO sec_admin.sensitive_columns VALUES ('SALES','CUSTOMERS','EMAIL', 'EMAIL', 'REDACT:REGEXP', 'mask_pkg.mask_email'); INSERT INTO sec_admin.sensitive_columns VALUES ('SALES','CUSTOMERS','CARD_NUMBER','CARD', 'REDACT:PARTIAL', 'mask_pkg.mask_card'); INSERT INTO sec_admin.sensitive_columns VALUES ('SALES','CUSTOMERS','NATIONAL_ID','NATIONAL_ID', 'REDACT:NULLIFY', 'mask_pkg.mask_national_id'); INSERT INTO sec_admin.sensitive_columns VALUES ('SALES','CUSTOMERS','BIRTH_DATE', 'DOB', 'REDACT:RANDOM', 'mask_pkg.shift_date'); INSERT INTO sec_admin.sensitive_columns VALUES ('SALES','CUSTOMERS','BALANCE', 'FINANCIAL', 'REDACT:FULL', 'none'); INSERT INTO sec_admin.sensitive_columns VALUES ('SALES','EMPLOYEES','SALARY', 'FINANCIAL', 'none', 'mask_pkg.mask_salary'); INSERT INTO sec_admin.sensitive_columns VALUES ('SALES','EMPLOYEES','EMAIL', 'EMAIL', 'none', 'mask_pkg.mask_email'); COMMIT; |
Why: name-based discovery is fast but misses COL17; content sampling catches the rest. SAMPLE(10) keeps the scan cheap on large tables. Write the inventory down once and reuse it — the same column must be redacted in production and masked in every copy, and the two lists drift apart unless they come from one place.
Part 1 — Data Redaction: protect values in production
Data Redaction rewrites column values at query time, in the result set only. Disk, redo, backups and the buffer cache keep the real data. A policy says which columns, how to mask them and for whom (a boolean expression evaluated per session).
Type | Result | Example |
FULL | Fixed value (0, space, 01-JAN-01) | balance → 0 |
PARTIAL | Part of the value replaced | 4532-1111-2222-3456 → ****-****-****-3456 |
REGEXP | Regular-expression replace | john.doe@acme.com → xxxx@acme.com |
RANDOM | Random value of the same datatype | date → random date |
NULLIFY | NULL | national id → NULL |
NONE | No redaction (test an expression) | — |
23ai additions: BOOLEAN columns can be redacted, and schema-level privileges (GRANT SELECT ANY TABLE ON SCHEMA sales TO ...) do not bypass a policy.
Step 1.1 — Create the policy with a FULL redaction on BALANCE
SQL |
-- as SEC_ADMIN in PROD_PDB BEGIN DBMS_REDACT.ADD_POLICY( object_schema => 'SALES', object_name => 'CUSTOMERS', policy_name => 'CUSTOMERS_REDACT_POL', column_name => 'BALANCE', function_type => DBMS_REDACT.FULL, expression => q'[SYS_CONTEXT('USERENV','SESSION_USER') NOT IN ('SALES_ADMIN','APP_USER')]'); END; / |
Why: one policy per table; the first ADD_POLICY creates it together with its first column. The expression is any boolean SQL built from SYS_CONTEXT (USERENV, SYS_SESSION_ROLES, your own application contexts); 1=1 means "redact for everybody except exempt users". FULL returns 0 for numbers, a space for strings and 01-JAN-01 for dates; change these database-wide with DBMS_REDACT.UPDATE_FULL_REDACTION_VALUES (needs a restart). Nobody is exempt by default — not even the table owner; only SYS and holders of EXEMPT REDACTION POLICY.
Step 1.2 — PARTIAL redaction on the card number
SQL |
BEGIN DBMS_REDACT.ALTER_POLICY( object_schema => 'SALES', object_name => 'CUSTOMERS', policy_name => 'CUSTOMERS_REDACT_POL', action => DBMS_REDACT.ADD_COLUMN, column_name => 'CARD_NUMBER', function_type => DBMS_REDACT.PARTIAL, function_parameters => DBMS_REDACT.REDACT_CCN16_F12); END; / |
Why: ALTER_POLICY ... ADD_COLUMN extends the existing policy. REDACT_CCN16_F12 is a shipped constant equal to 'VVVVFVVVVFVVVVFVVVV,VVVV-VVVV-VVVV-VVVV,*,1,12': input pattern (V = digit, F = formatting character), output pattern, mask character, first and last position to redact. Other shipped constants: REDACT_US_SSN_F5, REDACT_US_SSN_ENTIRE, REDACT_NUM_US_SSN_F5, REDACT_ZIP_CODE, REDACT_DATE_MILLENNIUM. For a NUMBER column the parameter is 'mask_digit,start,end', e.g. '9,1,5'. PARTIAL only works when the value matches the input pattern — if your data is not uniform, use REGEXP or FULL.
Step 1.3 — REGEXP redaction on the e-mail
SQL |
BEGIN DBMS_REDACT.ALTER_POLICY( object_schema => 'SALES', object_name => 'CUSTOMERS', policy_name => 'CUSTOMERS_REDACT_POL', action => DBMS_REDACT.ADD_COLUMN, column_name => 'EMAIL', function_type => DBMS_REDACT.REGEXP, regexp_pattern => DBMS_REDACT.RE_PATTERN_EMAIL_ADDRESS, regexp_replace_string => DBMS_REDACT.RE_REDACT_EMAIL_NAME, regexp_position => DBMS_REDACT.RE_BEGINNING, regexp_occurrence => DBMS_REDACT.RE_FIRST, regexp_match_parameter => DBMS_REDACT.RE_CASE_INSENSITIVE); END; / |
Why: regular-expression redaction handles free-form data (e-mails, phone numbers inside text, IP addresses). Oracle ships patterns (RE_PATTERN_EMAIL_ADDRESS, RE_PATTERN_CC_L6_T4, RE_PATTERN_US_PHONE, RE_PATTERN_IP_ADDRESS, RE_PATTERN_ANY_DIGIT) and replacements (RE_REDACT_EMAIL_NAME, RE_REDACT_EMAIL_DOMAIN, RE_REDACT_CC_MIDDLE_DIGITS, ...); you can also pass your own regex and a replace string with back-references.
Step 1.4 — RANDOM on the birth date, NULLIFY on the national id
SQL |
BEGIN DBMS_REDACT.ALTER_POLICY( object_schema => 'SALES', object_name => 'CUSTOMERS', policy_name => 'CUSTOMERS_REDACT_POL', action => DBMS_REDACT.ADD_COLUMN, column_name => 'BIRTH_DATE', function_type => DBMS_REDACT.RANDOM);
DBMS_REDACT.ALTER_POLICY( object_schema => 'SALES', object_name => 'CUSTOMERS', policy_name => 'CUSTOMERS_REDACT_POL', action => DBMS_REDACT.ADD_COLUMN, column_name => 'NATIONAL_ID', function_type => DBMS_REDACT.NULLIFY); END; / |
Why: RANDOM keeps the datatype and looks plausible on screens and in reports; NULLIFY is the safest choice when the value must never be shown but the column has to stay in the result set for the application.
Step 1.5 — Test as the application users
SQL |
CONNECT cc_agent/"Agent#2026"@prod_pdb SELECT cust_id, full_name, email, card_number, national_id, birth_date, balance FROM sales.customers; -- 1 John Doe xxxx@acme.com ****-****-****-3456 (null) <random> 0 -- 2 Jane Roe xxxx@acme.com ****-****-****-7777 (null) <random> 0
CONNECT app_user/"App#2026"@prod_pdb SELECT cust_id, balance FROM sales.customers; -- APP_USER is excluded by the expression: real values
-- WHERE clauses still evaluate real values: redaction applies to output only SELECT cust_id FROM sales.customers WHERE balance > 10000; -- returns 1 |
Why: the last query is the inference limitation — redaction protects displays and exports, not deduction. Pair it with least privilege and column-level unified auditing on the sensitive columns (see the Unified Auditing runbook).
Step 1.6 — Exempt the service accounts that must see clear data
SQL |
-- as SYS GRANT EXEMPT REDACTION POLICY TO etl_user; -- Data Pump exports (Step 2.5) run as this account |
Why: a non-exempt expdp fails with ORA-28081: Insufficient privileges - the command references a redacted object, and INSERT ... SELECT / CREATE TABLE AS SELECT by a non-exempt user produce redacted copies without any warning. Grant the exemption to the smallest possible set of accounts and audit it. This also matters for Part 2: policies are cloned together with the data, so the user that masks the clone must be exempt (or the policies must be disabled there first), otherwise it may be masking already-redacted values.
Step 1.7 — Reuse one expression across columns and tables
SQL |
BEGIN DBMS_REDACT.CREATE_POLICY_EXPRESSION( policy_expression_name => 'NOT_PII_VIEWER', expression => q'[SYS_CONTEXT('SYS_SESSION_ROLES','PII_VIEWER') = 'FALSE']', description => 'Redact unless the PII_VIEWER role is enabled in the session');
DBMS_REDACT.APPLY_POLICY_EXPR_TO_COL( object_schema => 'SALES', object_name => 'CUSTOMERS', column_name => 'CARD_NUMBER', policy_expression_name => 'NOT_PII_VIEWER'); END; / |
Why: a named expression applied to a column overrides the policy-level expression for that column, and one DBMS_REDACT.UPDATE_POLICY_EXPRESSION changes every column that uses it. Driving redaction by role (SYS_SESSION_ROLES) instead of by user name keeps the policy stable while people come and go.
Step 1.8 — Manage the policy over time
SQL |
-- change the policy-wide expression EXEC DBMS_REDACT.ALTER_POLICY(object_schema=>'SALES', object_name=>'CUSTOMERS', policy_name=>'CUSTOMERS_REDACT_POL', action=>DBMS_REDACT.MODIFY_EXPRESSION, expression=>q'[SYS_CONTEXT('SYS_SESSION_ROLES','PII_VIEWER') = 'FALSE']');
-- change how one column is redacted EXEC DBMS_REDACT.ALTER_POLICY(object_schema=>'SALES', object_name=>'CUSTOMERS', policy_name=>'CUSTOMERS_REDACT_POL', action=>DBMS_REDACT.MODIFY_COLUMN, column_name=>'BALANCE', function_type=>DBMS_REDACT.PARTIAL, function_parameters=>'9,1,3');
-- remove one column; pause / resume / drop the whole policy EXEC DBMS_REDACT.ALTER_POLICY(object_schema=>'SALES', object_name=>'CUSTOMERS', policy_name=>'CUSTOMERS_REDACT_POL', action=>DBMS_REDACT.DROP_COLUMN, column_name=>'BIRTH_DATE'); EXEC DBMS_REDACT.DISABLE_POLICY('SALES','CUSTOMERS','CUSTOMERS_REDACT_POL'); EXEC DBMS_REDACT.ENABLE_POLICY ('SALES','CUSTOMERS','CUSTOMERS_REDACT_POL'); EXEC DBMS_REDACT.DROP_POLICY ('SALES','CUSTOMERS','CUSTOMERS_REDACT_POL');
-- inventory and evidence SELECT object_owner, object_name, policy_name, expression, enable FROM redaction_policies; SELECT object_name, column_name, function_type, function_parameters, regexp_pattern FROM redaction_columns; SELECT policy_expression_name, expression FROM redaction_expressions; SELECT * FROM redaction_values_for_type_full; |
Why: REDACTION_POLICIES / REDACTION_COLUMNS are what you compare against SEC_ADMIN.SENSITIVE_COLUMNS: every prod_control that starts with REDACT: must have a matching row here.
Restrictions to remember: one policy per table or view; SYS-owned objects cannot be redacted; ORDER BY/GROUP BY and aggregates work on the real values (a SUM(balance) column is not redacted unless balance itself is the output column — test every report); materialized views over redacted columns are not allowed for non-exempt users; ORA-28094 means the query shape (e.g. some CONNECT BY or analytic constructs) is not supported.
Part 2 — Static masking: a safe copy for non-production
Step 2.1 — Clone production first
SQL |
-- in CDB23, as SYSDBA (same CDB; for another CDB use a database link — see the PDB migration runbook) CREATE PLUGGABLE DATABASE stage_pdb FROM prod_pdb FILE_NAME_CONVERT = ('/u02/oradata/CDB23/PROD_PDB/', '/u02/oradata/CDB23/STAGE_PDB/') -- omit with OMF KEYSTORE IDENTIFIED BY "Cdb#Keystore"; -- omit without TDE ALTER PLUGGABLE DATABASE stage_pdb OPEN;
ALTER SESSION SET CONTAINER = stage_pdb; SELECT object_name, policy_name, enable FROM redaction_policies; -- the policies came along with the clone EXEC DBMS_REDACT.DISABLE_POLICY('SALES','CUSTOMERS','CUSTOMERS_REDACT_POL'); -- or run the masking as an exempt user
-- clone only: the masking job needs DML and DDL on the application schema GRANT SELECT ANY TABLE, UPDATE ANY TABLE, DELETE ANY TABLE, ALTER ANY TABLE, ALTER ANY INDEX, CREATE ANY TABLE, DROP ANY TABLE, EXEMPT REDACTION POLICY TO sec_admin; |
Why: the clone is where masking runs; production is never touched. A refreshable clone (REFRESH MODE EVERY 1440 MINUTES) makes the next refresh cheap — see the PDB migration runbook. Disabling the redaction policies on the clone avoids masking redacted values and lets non-exempt developers test later; re-enable or drop them in DEV_PDB depending on whether the application should be tested with redaction on.
Step 2.2 — The masking package (deterministic, format-preserving)
SQL |
-- as SEC_ADMIN, in STAGE_PDB (and in PROD_PDB if you want to mask during export, Step 2.5) CREATE OR REPLACE PACKAGE sec_admin.mask_pkg AS FUNCTION mask_email (p_in VARCHAR2) RETURN VARCHAR2; FUNCTION mask_name (p_in VARCHAR2) RETURN VARCHAR2; FUNCTION mask_card (p_in VARCHAR2) RETURN VARCHAR2; FUNCTION mask_national_id (p_in VARCHAR2) RETURN VARCHAR2; FUNCTION shift_date (p_in DATE) RETURN DATE; FUNCTION mask_salary (p_in NUMBER) RETURN NUMBER; END mask_pkg; / CREATE OR REPLACE PACKAGE BODY sec_admin.mask_pkg AS c_salt CONSTANT VARCHAR2(64) := 'change-me-and-keep-me-secret'; -- rotate per environment, store outside the DB
TYPE t_names IS TABLE OF VARCHAR2(20); c_first CONSTANT t_names := t_names('Alex','Sam','Maria','Chen','Fatima','Lukas','Priya','Noah','Aisha','Tomas','Elena','Jonas'); c_last CONSTANT t_names := t_names('Weber','Garcia','Okafor','Novak','Tanaka','Dubois','Rossi','Kowalski','Haddad','Larsen','Silva','Berg');
-- keyed SHA-256 of the input, as 64 hex characters: same input => same output, not reversible without the salt FUNCTION hx (p_in VARCHAR2) RETURN VARCHAR2 IS BEGIN RETURN RAWTOHEX(DBMS_CRYPTO.HASH(UTL_RAW.CAST_TO_RAW(c_salt || UPPER(TRIM(p_in))), DBMS_CRYPTO.HASH_SH256)); END;
-- Luhn check digit so masked card numbers pass application validation FUNCTION luhn (p_payload VARCHAR2) RETURN VARCHAR2 IS l_sum NUMBER := 0; l_d NUMBER; l_double BOOLEAN := TRUE; BEGIN FOR i IN REVERSE 1 .. LENGTH(p_payload) LOOP l_d := TO_NUMBER(SUBSTR(p_payload, i, 1)); IF l_double THEN l_d := l_d * 2; IF l_d > 9 THEN l_d := l_d - 9; END IF; END IF; l_sum := l_sum + l_d; l_double := NOT l_double; END LOOP; RETURN TO_CHAR(MOD(10 - MOD(l_sum, 10), 10)); END;
FUNCTION mask_email (p_in VARCHAR2) RETURN VARCHAR2 IS BEGIN IF p_in IS NULL THEN RETURN NULL; END IF; RETURN 'user' || LOWER(SUBSTR(hx(p_in), 1, 12)) || '@example.com'; -- example.com never delivers mail END;
FUNCTION mask_name (p_in VARCHAR2) RETURN VARCHAR2 IS l_h VARCHAR2(64); BEGIN IF p_in IS NULL THEN RETURN NULL; END IF; l_h := hx(p_in); RETURN c_first(MOD(TO_NUMBER(SUBSTR(l_h, 1, 6), 'XXXXXX'), c_first.COUNT) + 1) || ' ' || c_last (MOD(TO_NUMBER(SUBSTR(l_h, 7, 6), 'XXXXXX'), c_last.COUNT) + 1); END;
FUNCTION mask_card (p_in VARCHAR2) RETURN VARCHAR2 IS l_payload VARCHAR2(15); l_out VARCHAR2(16); BEGIN IF p_in IS NULL THEN RETURN NULL; END IF; l_payload := '4' || SUBSTR(TRANSLATE(hx(p_in), 'ABCDEF', '012345'), 1, 14); -- 15 deterministic digits l_out := l_payload || luhn(l_payload); IF INSTR(p_in, '-') > 0 THEN -- keep the original formatting RETURN SUBSTR(l_out,1,4)||'-'||SUBSTR(l_out,5,4)||'-'||SUBSTR(l_out,9,4)||'-'||SUBSTR(l_out,13,4); END IF; RETURN l_out; END;
FUNCTION mask_national_id (p_in VARCHAR2) RETURN VARCHAR2 IS l_d VARCHAR2(9); BEGIN IF p_in IS NULL THEN RETURN NULL; END IF; l_d := LPAD(MOD(TO_NUMBER(SUBSTR(hx(p_in), 1, 8), 'XXXXXXXX'), 1000000000), 9, '0'); RETURN SUBSTR(l_d,1,3)||'-'||SUBSTR(l_d,4,2)||'-'||SUBSTR(l_d,6,4); END;
-- deterministic shift of 0..364 days into the past: age distribution survives, exact dates do not FUNCTION shift_date (p_in DATE) RETURN DATE IS BEGIN IF p_in IS NULL THEN RETURN NULL; END IF; RETURN p_in - MOD(TO_NUMBER(SUBSTR(hx(TO_CHAR(p_in,'YYYYMMDD')), 1, 4), 'XXXX'), 365); END;
-- random noise of +/- 15 %, rounded to hundreds: totals stay realistic, individuals are not identifiable FUNCTION mask_salary (p_in NUMBER) RETURN NUMBER IS BEGIN IF p_in IS NULL THEN RETURN NULL; END IF; RETURN ROUND(p_in * (0.85 + DBMS_RANDOM.VALUE(0, 0.30)), -2); END; END mask_pkg; / GRANT EXECUTE ON sec_admin.mask_pkg TO etl_user; -- Data Pump calls the functions as the exporting user (Step 2.5)
-- quick self-test SELECT sec_admin.mask_pkg.mask_email('john.doe@acme.com') AS email, sec_admin.mask_pkg.mask_name('John Doe') AS name, sec_admin.mask_pkg.mask_card('4532-1111-2222-3456') AS card, sec_admin.mask_pkg.mask_national_id('123-45-6789') AS nid, sec_admin.mask_pkg.shift_date(DATE '1985-03-14') AS dob FROM dual; |
Why: deterministic functions (same input → same output) are what keep the data usable: a customer's e-mail masked in CUSTOMERS and in a SUPPORT_TICKETS table still matches, unique constraints still hold, and a second refresh produces the same fake values so test scripts keep working. The salt makes the mapping non-reversible by a dictionary attack on known e-mails — keep it out of version control. Format preservation (dashes, Luhn, 999-99-9999) means application validation and screen layouts keep working. Random functions (mask_salary) are fine for measures that are never joined on. Never commit inside these functions — Data Pump calls them per row.
Step 2.3 — Mask in place on the clone (Option A)
SQL |
-- as SEC_ADMIN (exempt from redaction, policies disabled) in STAGE_PDB ALTER SESSION ENABLE PARALLEL DML; ALTER TABLE sales.customers DISABLE ALL TRIGGERS; -- audit/history triggers would record the masking
UPDATE /*+ PARALLEL(c 8) */ sales.customers c SET full_name = sec_admin.mask_pkg.mask_name(full_name), email = sec_admin.mask_pkg.mask_email(email), card_number = sec_admin.mask_pkg.mask_card(card_number), national_id = sec_admin.mask_pkg.mask_national_id(national_id), birth_date = sec_admin.mask_pkg.shift_date(birth_date); COMMIT;
UPDATE /*+ PARALLEL(e 8) */ sales.employees e SET full_name = sec_admin.mask_pkg.mask_name(full_name), email = sec_admin.mask_pkg.mask_email(email), salary = sec_admin.mask_pkg.mask_salary(salary); COMMIT;
ALTER TABLE sales.customers ENABLE ALL TRIGGERS; |
For tables with hundreds of millions of rows, chunk the update so each piece commits on its own and runs in parallel scheduler jobs:
SQL |
BEGIN DBMS_PARALLEL_EXECUTE.CREATE_TASK('MASK_CUSTOMERS'); DBMS_PARALLEL_EXECUTE.CREATE_CHUNKS_BY_ROWID( task_name => 'MASK_CUSTOMERS', table_owner => 'SALES', table_name => 'CUSTOMERS', by_row => TRUE, chunk_size => 200000); DBMS_PARALLEL_EXECUTE.RUN_TASK( task_name => 'MASK_CUSTOMERS', sql_stmt => 'UPDATE sales.customers SET full_name = sec_admin.mask_pkg.mask_name(full_name), email = sec_admin.mask_pkg.mask_email(email), card_number = sec_admin.mask_pkg.mask_card(card_number) WHERE rowid BETWEEN :start_id AND :end_id', language_flag => DBMS_SQL.NATIVE, parallel_level => 8); END; / SELECT status FROM user_parallel_execute_tasks WHERE task_name = 'MASK_CUSTOMERS'; -- FINISHED SELECT status, COUNT(*) FROM user_parallel_execute_chunks WHERE task_name = 'MASK_CUSTOMERS' GROUP BY status; EXEC DBMS_PARALLEL_EXECUTE.DROP_TASK('MASK_CUSTOMERS'); |
Afterwards:
SQL |
ALTER INDEX sales.customers_email_uk REBUILD PARALLEL 8; -- indexes on masked columns: rebuild, then NOPARALLEL ALTER INDEX sales.customers_email_uk NOPARALLEL; EXEC DBMS_STATS.GATHER_SCHEMA_STATS('SALES', degree => 8); |
Why: an in-place update rewrites every masked row, so expect redo and undo in the order of the table size — run the staging CDB in NOARCHIVELOG or size the FRA, and give UNDO room. DBMS_PARALLEL_EXECUTE turns one huge transaction into restartable chunks (RESUME_TASK after a failure). Columns that are foreign keys in other tables (a natural key such as EMAIL used by SUPPORT_TICKETS) must be masked with the same deterministic function in every table in the same job; surrogate numeric ids are left alone. Masked columns change their data distribution, so the statistics must be regathered.
Step 2.4 — Hand the masked clone to developers
SQL |
-- same CDB: clone again (fast with snapshot copy on capable storage), or unplug/plug or relocate to the dev CDB CREATE PLUGGABLE DATABASE dev_pdb FROM stage_pdb; ALTER PLUGGABLE DATABASE dev_pdb OPEN; |
Why: STAGE_PDB becomes the reusable "gold" masked image; every developer PDB is a cheap clone of it, and the next refresh is clone → mask → re-snapshot. Keep STAGE_PDB closed and its storage access restricted when not in use.
Step 2.5 — Mask on the way out with Data Pump (Option B, no staging clone)
Shell |
# mask.par — masking is applied while rows are written, so the dump never contains clear data SCHEMAS=sales DIRECTORY=dp_dir DUMPFILE=sales_masked_%U.dmp LOGFILE=sales_masked_exp.log PARALLEL=4 FLASHBACK_TIME=SYSTIMESTAMP ENCRYPTION=ALL ENCRYPTION_PASSWORD=Dump#Pwd2026 EXCLUDE=STATISTICS REMAP_DATA=sales.customers.full_name:sec_admin.mask_pkg.mask_name REMAP_DATA=sales.customers.email:sec_admin.mask_pkg.mask_email REMAP_DATA=sales.customers.card_number:sec_admin.mask_pkg.mask_card REMAP_DATA=sales.customers.national_id:sec_admin.mask_pkg.mask_national_id REMAP_DATA=sales.customers.birth_date:sec_admin.mask_pkg.shift_date REMAP_DATA=sales.employees.full_name:sec_admin.mask_pkg.mask_name REMAP_DATA=sales.employees.email:sec_admin.mask_pkg.mask_email REMAP_DATA=sales.employees.salary:sec_admin.mask_pkg.mask_salary |
Shell |
expdp etl_user@prod_pdb PARFILE=mask.par # exempt from redaction (Step 1.6); a non-exempt user gets ORA-28081 |
Why: REMAP_DATA=schema.table.column:package.function calls the function for every value as it is unloaded. The function must be a packaged function, accept and return the column's datatype, must not commit, and the user running Data Pump needs EXECUTE on it (granted in Step 2.2). FLASHBACK_TIME makes the export consistent across tables, EXCLUDE=STATISTICS avoids importing statistics that describe unmasked data, and the dump is encrypted because it still leaves the production host. Tables with REMAP_DATA/QUERY are unloaded through the external-table path instead of direct path, so expect it to be slower than a plain export. LONG columns and LOB columns read over NETWORK_LINK cannot be remapped — mask those in place after import. Masking on the import side (impdp ... REMAP_DATA=...) also works, but then the dump holds real data: use it only inside the production security zone.
Step 2.6 — Import into the dev PDB
Shell |
impdp system@dev_pdb \ DIRECTORY=dp_dir DUMPFILE=sales_masked_%U.dmp LOGFILE=sales_masked_imp.log \ REMAP_TABLESPACE=sales_data:users \ TRANSFORM=DISABLE_ARCHIVE_LOGGING:Y \ ENCRYPTION_PASSWORD=Dump#Pwd2026 |
SQL |
EXEC DBMS_STATS.GATHER_SCHEMA_STATS('SALES', degree => 4); |
Why: TRANSFORM=DISABLE_ARCHIVE_LOGGING:Y speeds up the load in a PDB whose data is disposable; remap tablespaces if dev has a simpler storage layout; gather statistics because they were excluded on purpose.
Part 3 — Subsetting: keep only what the test needs
Step 3.1 — Decide the driving set and map the dependencies
SQL |
-- driving rule: customers from DE/AT/CH; everything that hangs off them follows -- which tables hang off CUSTOMERS, and in which order? SELECT LEVEL AS depth, LPAD(' ', 2*(LEVEL-1)) || c.table_name AS child_table, r.table_name AS parent_table, c.constraint_name FROM dba_constraints c JOIN dba_constraints r ON r.owner = c.r_owner AND r.constraint_name = c.r_constraint_name WHERE c.constraint_type = 'R' AND c.owner = 'SALES' START WITH r.table_name = 'CUSTOMERS' CONNECT BY NOCYCLE PRIOR c.table_name = r.table_name; -- 1 ORDERS CUSTOMERS ORDERS_CUST_FK -- 2 ORDER_ITEMS ORDERS ORDER_ITEMS_ORDER_FK
-- application-enforced relationships (no FK constraint) must be added by hand: ask the developers |
Why: a subset is only usable if every child row's parent is in the subset. Declared foreign keys give you most of the graph; relationships enforced only by application code are the ones that produce orphan rows and failed constraint enablement later, so find them now. Reference and lookup tables (PRODUCTS, COUNTRIES) are copied in full.
Step 3.2 — Subset (and mask) during export with QUERY
Shell |
# subset.par — one QUERY per table, each one following the foreign keys back to the driving table SCHEMAS=sales DIRECTORY=dp_dir DUMPFILE=sales_subset_%U.dmp LOGFILE=sales_subset_exp.log PARALLEL=4 FLASHBACK_TIME=SYSTIMESTAMP ENCRYPTION=ALL ENCRYPTION_PASSWORD=Dump#Pwd2026 EXCLUDE=STATISTICS QUERY=sales.customers:"WHERE country IN ('DE','AT','CH')" QUERY=sales.orders:"WHERE cust_id IN (SELECT cust_id FROM sales.customers WHERE country IN ('DE','AT','CH'))" QUERY=sales.order_items:"WHERE order_id IN (SELECT o.order_id FROM sales.orders o JOIN sales.customers c ON c.cust_id = o.cust_id WHERE c.country IN ('DE','AT','CH'))" SAMPLE=sales.web_clicks:5 REMAP_DATA=sales.customers.full_name:sec_admin.mask_pkg.mask_name REMAP_DATA=sales.customers.email:sec_admin.mask_pkg.mask_email REMAP_DATA=sales.customers.card_number:sec_admin.mask_pkg.mask_card REMAP_DATA=sales.customers.national_id:sec_admin.mask_pkg.mask_national_id REMAP_DATA=sales.customers.birth_date:sec_admin.mask_pkg.shift_date |
Shell |
expdp etl_user@stage_pdb PARFILE=subset.par # from the masked clone (Part 2) or straight from PROD_PDB with REMAP_DATA |
Why: QUERY=schema.table:"WHERE ..." is appended to the unload of that table; subqueries are allowed and are how child tables follow their parents. Tables without a QUERY are exported completely (that is what you want for lookup tables). SAMPLE=table:percent picks random rows and therefore breaks referential integrity — use it only on standalone tables such as click logs. Use a parameter file: the quotes inside QUERY are hostile to shell escaping. Combining QUERY and REMAP_DATA in one run gives you the masked subset in a single pass.
Step 3.3 — Subset in place on the clone instead (big tables, complex graphs)
SQL |
-- in STAGE_PDB: delete what is NOT in the subset, children first, then parents ALTER SESSION ENABLE PARALLEL DML;
DELETE /*+ PARALLEL(8) */ FROM sales.order_items WHERE order_id IN (SELECT o.order_id FROM sales.orders o JOIN sales.customers c ON c.cust_id = o.cust_id WHERE c.country NOT IN ('DE','AT','CH')); DELETE /*+ PARALLEL(8) */ FROM sales.orders WHERE cust_id IN (SELECT cust_id FROM sales.customers WHERE country NOT IN ('DE','AT','CH')); DELETE /*+ PARALLEL(8) */ FROM sales.customers WHERE country NOT IN ('DE','AT','CH'); COMMIT;
-- when "keep 5 %" means dropping 95 % of a huge table, copying the keepers is far cheaper than deleting CREATE TABLE sales.orders_keep PARALLEL 8 NOLOGGING AS SELECT * FROM sales.orders WHERE cust_id IN (SELECT cust_id FROM sales.customers); -- then: drop FKs/indexes pointing at ORDERS, DROP TABLE sales.orders, RENAME orders_keep TO orders, recreate PK/FKs/indexes/grants ALTER TABLE sales.orders_keep LOGGING; EXEC DBMS_STATS.GATHER_SCHEMA_STATS('SALES', degree => 8); |
Why: in-place subsetting lets you reuse the clone/snapshot workflow of Part 2 and avoids writing a dump at all; delete order matters because the foreign keys are enforced. A CTAS-and-swap rewrites only the rows you keep and leaves no empty blocks behind, but you have to recreate everything that depended on the old table — script it once and keep it in version control.
Step 3.4 — Import and repair
Shell |
impdp system@dev_pdb DIRECTORY=dp_dir DUMPFILE=sales_subset_%U.dmp LOGFILE=sales_subset_imp.log \ REMAP_TABLESPACE=sales_data:users TRANSFORM=DISABLE_ARCHIVE_LOGGING:Y ENCRYPTION_PASSWORD=Dump#Pwd2026 |
SQL |
-- orphans: must all be 0 (an orphan makes impdp fail the FK with ORA-02298) SELECT COUNT(*) FROM sales.orders o WHERE NOT EXISTS (SELECT 1 FROM sales.customers c WHERE c.cust_id = o.cust_id); SELECT COUNT(*) FROM sales.order_items i WHERE NOT EXISTS (SELECT 1 FROM sales.orders o WHERE o.order_id = i.order_id);
-- constraints enabled and validated SELECT constraint_name, table_name, status, validated FROM dba_constraints WHERE owner = 'SALES' AND constraint_type = 'R' AND (status <> 'ENABLED' OR validated <> 'VALIDATED');
-- sequences: a subset keeps the production sequence values; nothing to do unless you reseed on purpose SELECT table_name, num_rows FROM dba_tables WHERE owner = 'SALES' ORDER BY 1; |
Why: if a QUERY missed a relationship, the import log shows the FK creation failing; the orphan queries tell you which table, and the fix is a better QUERY (or deleting the orphans in dev when the test does not need them).
Part 4 — Validate before hand-over
SQL |
-- 1) no production value survived (run in DEV_PDB; compare with a production checksum obtained by an exempt user) SELECT COUNT(*) FROM sales.customers WHERE email NOT LIKE '%@example.com'; -- 0 SELECT COUNT(*) FROM sales.customers WHERE REGEXP_LIKE(card_number, '^(4532|5100)'); -- 0: no known real prefixes SELECT SUM(ORA_HASH(national_id)) AS checksum FROM sales.customers; -- differs from the same query in prod
-- 2) structure intact SELECT owner, object_type, COUNT(*) FROM dba_objects WHERE owner = 'SALES' AND status = 'INVALID' GROUP BY owner, object_type; SELECT constraint_name FROM dba_constraints WHERE owner = 'SALES' AND status <> 'ENABLED'; SELECT index_name, status FROM dba_indexes WHERE owner = 'SALES' AND status NOT IN ('VALID','N/A');
-- 3) redaction state in the copy is what you decided (Step 2.1) SELECT object_name, policy_name, enable FROM redaction_policies;
-- 4) nothing sensitive left behind on the way SELECT directory_name, directory_path FROM dba_directories WHERE directory_name = 'DP_DIR'; -- delete or encrypt the dumps |
Why: the masked copy is only "safe" once you have proven it: a query that finds zero real values, constraints and indexes that came back enabled, and dump files that are gone. Store the three scripts (discovery, masking package, export parameter files) in version control so the next refresh is a repeat, not a project.
Checklist
☐ Sensitive-column inventory (SEC_ADMIN.SENSITIVE_COLUMNS) reviewed and signed off
☐ Production: redaction policy covers every REDACT:* column; exemptions limited to named service accounts and audited
☐ Reports tested with redaction on (aggregates, ORDER BY, exports)
☐ Clone taken; redaction policies disabled on the clone or masking user exempt
☐ Every non-production copy of a sensitive column has a masking function; deterministic functions on join keys and unique columns; same function for the same data in every table
☐ Masking salt stored outside the database and version control
☐ Subset QUERY list follows every relationship, including application-enforced ones; lookup tables complete
☐ After masking/subsetting: constraints enabled, indexes valid, objects valid, statistics regathered
☐ Zero real values found by the validation queries; dumps and staging clones deleted or encrypted
☐ Discovery SQL, masking package, parameter files and swap scripts in version control
Common errors
Error | Cause / fix |
ORA-28060: A policy already exists on column | use ALTER_POLICY ... MODIFY_COLUMN |
ORA-28069: A policy already exists on the specified object | one policy per table: add columns with ALTER_POLICY ... ADD_COLUMN |
ORA-28081: Insufficient privileges - the command references a redacted object | expdp/CTAS by a non-exempt user; grant EXEMPT REDACTION POLICY or disable the policy on the clone |
ORA-28094: SQL construct not supported by data redaction | query shape not supported (some CONNECT BY/analytic forms); rewrite or exempt the account |
ORA-39001: invalid argument value on REMAP_DATA | function not in a package, wrong datatype, or no EXECUTE for the Data Pump user |
ORA-00001: unique constraint violated during masking | non-deterministic function on a unique column, or two inputs mapped to one output — hash more characters or append the key |
ORA-02298: cannot validate (SALES.ORDERS_CUST_FK) - parent keys not found | subset QUERY missed a relationship; fix the query or delete the orphans |
ORA-01555 / ORA-30036 during in-place masking | undo too small for one giant transaction; use DBMS_PARALLEL_EXECUTE chunks |
ORA-39071: Value for QUERY is badly formed | the clause must start with WHERE, be quoted in the parameter file and name the table as schema.table |
Comments