Snowflake Dynamic Data Masking
One copy of the data, many different answers
Dynamic data masking is a query-time transformation attached to a column. The stored bytes never change: what changes is the value a session receives, decided by a SQL expression that can branch on the current role, the current warehouse, the hour of the day, or any other session context. That distinction matters for operations, because there is no second copy of the table to refresh, no ETL job that produces a masked variant, and no risk that the masked and unmasked tables drift apart.
The practical consequence is that access control moves from the table level to the value level. A support agent and a fraud analyst can both be granted SELECT on the same customer table and still see different contents, which is exactly what auditors ask for when they want to know who can see a full account number.
- Attach one masking policy per protected column; the policy itself carries the branching logic.
- Decide visibility by role, not by individual user, so grants stay manageable.
- Prove coverage with POLICY_REFERENCES and prove use with ACCESS_HISTORY.
Prerequisites
- !Snowflake roles and grants
- !Basic SQL CASE expressions
What You'll Learn
- 1Write masking policies that branch on CURRENT_ROLE() and session context
- 2Choose full, partial, hash, and null transformations by sensitivity level
- 3Apply, replace, and remove policies across many columns safely
- 4Audit which columns are protected and who has queried them
Anatomy of a masking policy
A masking policy is a named object with a single argument â the column value â and a return type that must match the column's type exactly. Everything interesting happens inside a CASE expression whose branches are the visibility tiers you have defined. Snowflake caches the compiled policy, so the added cost per row is the evaluation of that expression rather than a lookup against a catalogue.
CREATE OR REPLACE MASKING POLICY customer_pii AS (val STRING)
RETURNS STRING ->
CASE
WHEN CURRENT_ROLE() IN ('ACCOUNTADMIN', 'SECURITY_OFFICER') THEN val
WHEN CURRENT_ROLE() = 'AUDITOR' THEN SHA2_HEX(val, 256)
WHEN CURRENT_ROLE() = 'SUPPORT_AGENT'
THEN CONCAT(SUBSTRING(val, 1, 2),
REPEAT('*', GREATEST(LENGTH(val) - 4, 0)),
SUBSTRING(val, GREATEST(LENGTH(val) - 1, 1)))
ELSE '***MASKED***'
END;
-- Attach to a column: one active policy per column
ALTER TABLE raw.customer
MODIFY COLUMN email SET MASKING POLICY customer_pii;
ALTER TABLE raw.customer
MODIFY COLUMN phone SET MASKING POLICY customer_pii;
-- Detach returns the column to its stored values
ALTER TABLE raw.customer
MODIFY COLUMN email UNSET MASKING POLICY;
Two rules govern the shape of the policy. First, the argument type and return type must both match the column type, so a VARCHAR column needs a STRING policy and a NUMBER column needs a NUMBER policy â you cannot reuse one policy across both. Second, the final ELSE branch is your safety net: a role nobody has thought about must land in the most restrictive branch, never in the permissive one. Policies that default to showing data fail open, and failing open is how masked columns end up unmasked in a report.
A useful property of this design is that the same policy can be attached to many columns, so the branching logic exists in one place. When the security team adds a new analyst role, you edit the policy once rather than hunting through every ALTER TABLE statement that ever touched a customer column.
Session context beyond the role
Roles are the primary key of masking decisions, but they are not the only input available. The current warehouse, the current account, the hour of day, and even user-defined session variables can all participate, which lets one policy express conditions that would otherwise require several policies and application logic.
-- Business-hours rule: full access only in working hours
CREATE OR REPLACE MASKING POLICY time_aware AS (val STRING)
RETURNS STRING ->
CASE
WHEN CURRENT_ROLE() = 'SECURITY_OFFICER' THEN val
WHEN CURRENT_ROLE() = 'ANALYST'
AND HOUR(CURRENT_TIMESTAMP()) BETWEEN 8 AND 18
THEN CONCAT(SUBSTRING(val, 1, 3), '***', SUBSTRING(val, -3))
ELSE '***OUTSIDE-HOURS***'
END;
-- Warehouse-based rule: anything running on a shared external
-- warehouse is treated as untrusted
CREATE OR REPLACE MASKING POLICY warehouse_aware AS (val STRING)
RETURNS STRING ->
CASE
WHEN CURRENT_ROLE() IN ('ACCOUNTADMIN', 'DATA_ENGINEER') THEN val
WHEN CURRENT_WAREHOUSE() IN ('PARTNER_WH', 'SHARED_WH')
THEN CONCAT('ext_', HASH(val, 256))
ELSE val
END;
-- Session variable set by the application before the query
ALTER SESSION SET APP_TIER = 'viewer';
CREATE OR REPLACE MASKING POLICY tier_aware AS (val STRING)
RETURNS STRING ->
CASE
WHEN CURRENT_ROLE() = 'ACCOUNTADMIN' THEN val
WHEN CURRENT_SESSION() LIKE '%APP%' AND CURRENT_SETTING('APP_TIER') = 'admin'
THEN val
ELSE '***TIER-RESTRICTED***'
END;
Time-based branches are attractive but deserve scrutiny: they make results depend on when a query ran, which can break reproducible analyses and complicate incident investigations. Warehouse-based rules are usually easier to justify, because the warehouse a job uses is a deliberate architectural choice rather than a clock reading. Whichever context you use, write down the rule in the policy comment so the next engineer can predict what a given session will see without running a query.
Choosing a transformation by sensitivity
Not every protected column needs the same treatment, and over-masking is almost as damaging as under-masking: a support agent who cannot see the last four digits of a card cannot verify identity, and escalates everything instead.
| Sensitivity | Transformation | Example output | Reversible | Typical columns |
|---|---|---|---|---|
| Restricted | full mask | ***MASKED*** | no | SSN, national ID, full card number |
| High | partial reveal | (***) ***-4821 | no | phone, account number |
| Medium | domain-preserving | j***@acme.com | no | email, username |
| Matching | deterministic hash | 9f2c...e1a7 | no | join keys across systems |
| Encrypted | AES encryption | ciphertext | yes, with key | fields needing later recovery |
| Low | truncation or rounding | 2026-03-01, 1200 | no | dates, amounts |
Hashing deserves particular care. HASH(val, 256) is deterministic, so the same input always produces the same output, which means you can still join a masked column against another system's masked column without either side revealing values. That is the property that makes hashing the right answer for a privacy-preserving key. It is also why hashing is a poor choice for low-entropy secrets such as four-digit PINs: an attacker with a hash can enumerate the small input space offline. Use a salted or keyed construction for those, or keep them fully masked.
-- Deterministic hash for cross-system matching
CREATE OR REPLACE MASKING POLICY matchable_hash AS (val STRING)
RETURNS STRING ->
CASE WHEN CURRENT_ROLE() IN ('ACCOUNTADMIN', 'TOKENIZER') THEN val
ELSE SHA2_HEX(CONCAT('tenant-7::', val), 256)
END;
-- Partial reveal for verification workflows
CREATE OR REPLACE MASKING POLICY card_tail AS (val STRING)
RETURNS STRING ->
CASE WHEN CURRENT_ROLE() = 'FRAUD_ANALYST' THEN val
WHEN CURRENT_ROLE() IN ('SUPPORT_AGENT', 'ANALYST')
THEN CONCAT('****-****-****-', SUBSTRING(val, -4))
ELSE '****-****-****-****'
END;
-- Numeric granularity by role
CREATE OR REPLACE MASKING POLICY amount_precision AS (val NUMBER)
RETURNS NUMBER ->
CASE WHEN CURRENT_ROLE() = 'ACCOUNTADMIN' THEN val
WHEN CURRENT_ROLE() = 'FINANCE' THEN ROUND(val, 2)
WHEN CURRENT_ROLE() = 'ANALYST' THEN ROUND(val, -2)
ELSE 0
END;
-- Date granularity by role
CREATE OR REPLACE MASKING POLICY event_date AS (val DATE)
RETURNS DATE ->
CASE WHEN CURRENT_ROLE() = 'ACCOUNTADMIN' THEN val
WHEN CURRENT_ROLE() = 'ANALYST' THEN DATE_TRUNC('MONTH', val)
WHEN CURRENT_ROLE() = 'REPORTING' THEN DATE_TRUNC('YEAR', val)
ELSE '1900-01-01'::DATE
END;
Numeric and date policies are where role-based granularity pays off most visibly. Rounding an amount to the nearest hundred for analysts preserves distributional analysis â means, trends, percentiles stay meaningful â while preventing anyone from reading a specific transaction value. Truncating dates to the month preserves cohort and seasonality work and removes the ability to pinpoint an individual event.
Rolling a policy out across a warehouse
Attaching a policy is a metadata operation and is effectively instantaneous, but discovering which columns still lack protection is the harder problem. INFORMATION_SCHEMA.POLICY_REFERENCES answers coverage questions directly, and writing the check as a query means you can schedule it.
-- Which columns does this policy protect?
SELECT ref_database_name, ref_schema_name, ref_entity_name, ref_entity_domain
FROM TABLE(INFORMATION_SCHEMA.POLICY_REFERENCES(
POLICY_NAME => 'customer_pii'
));
-- Which policies does this table use?
SELECT policy_name, ref_entity_name, column_name
FROM TABLE(INFORMATION_SCHEMA.POLICY_REFERENCES(
REF_ENTITY_NAME => 'raw.customer',
REF_ENTITY_DOMAIN => 'TABLE'
));
-- Every masking policy in the account
SHOW MASKING POLICIES;
DESC MASKING POLICY customer_pii;
-- Columns holding likely PII that have no policy attached
SELECT table_schema, table_name, column_name, data_type
FROM information_schema.columns
WHERE table_schema NOT IN ('INFORMATION_SCHEMA')
AND (REGEXP_LIKE(column_name, 'email|phone|ssn|card|dob', 'i'))
AND NOT EXISTS (
SELECT 1
FROM TABLE(INFORMATION_SCHEMA.POLICY_REFERENCES(
REF_ENTITY_NAME => table_schema || '.' || table_name,
REF_ENTITY_DOMAIN => 'TABLE'
)) p
WHERE p.column_name = information_schema.columns.column_name
);
That last query is the one worth putting on a schedule. Coverage gaps are created by ordinary development â someone adds a phone_number column during a sprint, ships the migration, and nobody remembers the masking step â and a weekly report that lists unprotected PII columns converts that silent drift into a ticket.
Proving use, not just coverage
Coverage says a policy exists; access history says whether anyone actually queried the column and under which role. Together they are the evidence an auditor asks for, and both live in Snowflake's usage views.
-- Who queried the customer table in the last week?
SELECT
query_id,
user_name,
role_name,
query_start_time,
direct_objects_accessed
FROM snowflake.account_usage.access_history
WHERE query_start_time >= DATEADD(day, -7, CURRENT_TIMESTAMP())
AND IS_OBJECT_VALUE_IN_OBJECT(direct_objects_accessed, 'RAW.CUSTOMER')
ORDER BY query_start_time DESC;
-- Volume of reads per role against a protected schema
SELECT
role_name,
COUNT(*) AS queries,
COUNT(DISTINCT user_name) AS users
FROM snowflake.account_usage.query_history
WHERE start_time >= DATEADD(day, -30, CURRENT_TIMESTAMP())
AND query_type = 'SELECT'
AND query_text ILIKE '%raw.customer%'
GROUP BY role_name
ORDER BY queries DESC;
-- Masking events are visible in the returned data, not as log lines:
-- sample the view under two roles and diff the results
USE ROLE SUPPORT_AGENT;
SELECT email, phone FROM raw.customer LIMIT 5;
USE ROLE SECURITY_OFFICER;
SELECT email, phone FROM raw.customer LIMIT 5;
The sampling step at the end is not decoration. A policy can be present, attached, and syntactically valid while its CASE never matches the role you intended â a typo in a role name falls through to the ELSE. Testing the view under each real role is the only way to confirm the branches behave, and it takes thirty seconds.
Performance and storage characteristics
Masking adds no storage: there is no shadow column, no materialised variant, and no background job keeping a copy in sync. The only cost is evaluating the policy expression per returned row, and because policies are cached in the cloud services layer after first use, that evaluation is a simple CASE rather than a metadata lookup. In practice the overhead is well under one per cent of query time for string policies and slightly higher for cryptographic hashing, which performs real computation on every row.
| Policy type | Per-row work | Relative overhead | Notes |
|---|---|---|---|
| Full mask | constant replacement | negligible | cheapest option |
| Partial mask | substring and concatenate | very low | depends on string length |
| Numeric rounding | one arithmetic op | negligible | preserves aggregates |
| Deterministic hash | SHA-256 over the value | low to moderate | scales with value length |
| AES encryption | block cipher | moderate | key management required |
One operational caveat: policies participate in the query plan, so changing a policy can change the optimiser's estimate for a query even though no table statistics moved. If a dashboard's performance shifts immediately after a policy edit, check the plan before investigating the warehouse.
Mistakes that quietly defeat masking
Common Mistakes
Letting the final ELSE branch return the original value
Fix: Default to the most restrictive branch so unknown roles fail closed rather than open.
Assuming a policy applies because the table was altered in a script
Fix: Verify with POLICY_REFERENCES after every deployment; the alter statement may have run against the wrong environment.
Reusing one policy on columns of different data types
Fix: Argument and return types must match the column type, so STRING and NUMBER columns need separate policies.
Hashing low-entropy values such as PINs or short codes
Fix: A deterministic hash of a small input space is reversible by enumeration; mask fully or use a keyed construction.
Relying on masking as the only control
Fix: Combine it with column grants and row access policies so a compromised role cannot simply select the raw column.
Never testing the view under each role
Fix: A typo in a role name makes the branch unreachable; sample the table under every tier before sign-off.
Forgetting new columns added by later migrations
Fix: Schedule the unmatched-PII-column query so coverage gaps appear as tickets instead of findings.
Practices that keep masking governable
Best Practices
- Design tiers around roles rather than individual users so grants remain enumerable.
- Version-control every policy definition and deploy it through the same pipeline as table changes.
- Name policies by data class, not by table, so reuse across tables is obvious.
- Document the branching rule in the policy comment, including which roles fall into ELSE.
- Pair masking with column-level grants; the two controls catch different failure modes.
- Run POLICY_REFERENCES coverage checks on a schedule and route the output to the security backlog.
- Review time-based rules annually, since they make query results depend on wall-clock time.
- For payment card data, prefer an external tokenisation service over in-database masking where PCI scope is a concern.
Key takeaways
Key Takeaways
- Masking policies transform values at query time, so stored data stays singular and unmodified.
- One policy can protect many columns, which puts role branching in a single editable place.
- Match the transformation to the sensitivity: full mask for identifiers, partial for verification, hashing for matching.
- Numeric and date granularity lets analysts keep working while individual values stay hidden.
- Coverage is proven with POLICY_REFERENCES; actual use is proven with ACCESS_HISTORY.
- Unknown roles must fall into the restrictive ELSE branch, and every branch should be tested under a real role.
- Storage overhead is zero and query overhead is normally under one per cent, so cost is rarely the constraint.
Where to go next
- Access Control â the role and grant model that masking decisions branch on.
- Security Best Practices â layering masking with grants, policies, and network rules.
- Governance â classification, tagging, and the policies that drive masking requirements.
- Access History â the audit view used above to prove who read what.