Applications frequently store sensitive information such as email addresses, phone numbers, customer details, salaries, and account numbers. Not every user who needs access to a database should be able to see all this information.
For example, a customer support employee may need to search customer records and verify account details without seeing complete phone numbers or email addresses. Similarly, a reporting user may need access to employee records without viewing their actual salaries.
SQL Server provides Dynamic Data Masking (DDM) to help control how sensitive column values appear in query results. It allows database administrators to define masking rules on selected columns and control which users can view the original values.
Dynamic Data Masking does not change the data stored in the database. Instead, SQL Server applies the masking rule when an authorized query returns data to a user who does not have permission to view the unmasked values.
In this article, we will explore how Dynamic Data Masking works, configure different masking functions, manage UNMASK permissions, and understand its security limitations in production applications.
Understanding Dynamic Data Masking
Dynamic Data Masking is a SQL Server security feature that limits the exposure of sensitive information in query results.
Consider a customer table containing the following information:
A support employee may need to identify customers but should not see their complete contact information.
With Dynamic Data Masking, the database administrator can define rules that display masked values to users without the required permission.
For example, the email address may appear as [email protected], while the phone number may appear as a masked value.
The original information remains unchanged in the database. Users with the appropriate UNMASK permission can still retrieve the original values.
This makes Dynamic Data Masking useful for reducing accidental exposure of sensitive information in application queries, reporting tools, and development environments.
How Dynamic Data Masking Works
Dynamic Data Masking is configured at the column level. When a user executes a SELECT query, SQL Server checks the user's permissions and applies the configured masking function when necessary.
The process can be understood through three steps:
A database administrator defines a masking function on a sensitive column.
A user receives SELECT permission but does not receive UNMASK permission.
SQL Server returns the masked representation of the column value to that user.
Users with sufficient permissions, such as UNMASK, can retrieve the original values.
<AsyncImage query="SQL Server dynamic data masking database security architecture masked query results authorized unauthorized users diagram" aspectRatio="16:9" width="100%"/>
It is important to understand that masking affects the presentation of query results, not the underlying stored data. SQL Server continues to store and process the original values.
Types of Dynamic Data Masking Functions
SQL Server provides several built-in masking functions. Each function is designed for a different type of data.
Default Masking
The default function applies a predefined masked value based on the column's data type.
For example, string values are displayed using X characters, numeric values are displayed as zero, and date values use a default date.
CREATE TABLE dbo.Employees
(
EmployeeId INT PRIMARY KEY,
EmployeeName VARCHAR(100),
Salary DECIMAL(12, 2)
MASKED WITH (FUNCTION = 'default()'),
BirthDate DATE
MASKED WITH (FUNCTION = 'default()')
);
A user without UNMASK permission will see the masked representation of the salary and birth date.
Default masking is useful when the application does not need to display any part of the original value.
Email Masking
The email function displays an email-like masked value while exposing limited information.
CREATE TABLE dbo.Customers
(
CustomerId INT PRIMARY KEY,
Email VARCHAR(150)
MASKED WITH (FUNCTION = 'email()')
);
An email address such as [email protected] may appear as [email protected].
This function is useful when users need to recognize that a field contains an email address without seeing the complete value.
Partial Masking
The partial function allows administrators to expose a selected number of characters at the beginning and end of a string while replacing the middle portion with a specified padding value.
Its general syntax is:
partial(prefix, "padding", suffix)
For example:
CREATE TABLE dbo.CustomerDetails
(
CustomerId INT PRIMARY KEY,
PhoneNumber VARCHAR(20)
MASKED WITH (FUNCTION = 'partial(2,"XXXXXX",2)')
);
A phone number such as 9876543210 can be displayed with its first two and last two characters visible.
Partial masking is useful for phone numbers, account references, and other identifiers where users need limited information for verification.
Random Masking
The random function applies a random value within a specified range to numeric columns.
CREATE TABLE dbo.EmployeeCompensation
(
EmployeeId INT PRIMARY KEY,
Salary INT
MASKED WITH (FUNCTION = 'random(10000, 50000)')
);
A user without UNMASK permission sees a generated value within the configured range instead of the actual salary.
This function can be useful when users need to see a numeric value without accessing the original value.
However, the displayed value is not a secure substitute for realistic test data or statistical anonymization. Do not use it when reports depend on accurate numerical relationships.
Creating a Table With Multiple Masking Rules
A practical application usually needs to protect several types of sensitive information.
The following example creates a customer table with different masking functions.
CREATE TABLE dbo.CustomerInformation
(
CustomerId INT IDENTITY(1,1) PRIMARY KEY,
CustomerName VARCHAR(100)
MASKED WITH (FUNCTION = 'partial(1,"XXXX",1)'),
Email VARCHAR(150)
MASKED WITH (FUNCTION = 'email()'),
PhoneNumber VARCHAR(20)
MASKED WITH (FUNCTION = 'partial(2,"XXXXXX",2)'),
AccountBalance DECIMAL(12,2)
MASKED WITH (FUNCTION = 'default()')
);
Insert some sample records:
INSERT INTO dbo.CustomerInformation
(
CustomerName,
Email,
PhoneNumber,
AccountBalance
)
VALUES
(
'Rahul Sharma',
'[email protected]',
'9876543210',
45000.50
),
(
'Priya Verma',
'[email protected]',
'9876501234',
72000.00
);
The table stores the original values. Masking is applied when a user without the required permission queries the data.
Applying Dynamic Data Masking to Existing Columns
You do not need to recreate a table to apply Dynamic Data Masking. SQL Server allows administrators to add a masking rule to an existing column through ALTER TABLE.
For example, to mask an existing email column:
ALTER TABLE dbo.Customers
ALTER COLUMN Email
ADD MASKED WITH (FUNCTION = 'email()');
To apply partial masking to an existing phone number column:
ALTER TABLE dbo.Customers
ALTER COLUMN PhoneNumber
ADD MASKED WITH
(
FUNCTION = 'partial(2,"XXXXXX",2)'
);
You can also change an existing masking function.
ALTER TABLE dbo.Customers
ALTER COLUMN Email VARCHAR(150)
MASKED WITH (FUNCTION = 'default()');
To remove masking from a column:
ALTER TABLE dbo.Customers
ALTER COLUMN Email
DROP MASKED;
These operations change the masking configuration, not the original stored values.
Managing UNMASK Permissions
Defining a masking rule is only one part of Dynamic Data Masking. Administrators must also control which users can retrieve the original values.
A user with SELECT permission can query a masked column, but SQL Server returns the masked representation unless the user also has the required UNMASK permission.
Create a test user:
CREATE USER SupportEmployee WITHOUT LOGIN;
Grant access to the customer table:
GRANT SELECT
ON dbo.CustomerInformation
TO SupportEmployee;
Now test the query using that user's security context:
EXECUTE AS USER = 'SupportEmployee';
SELECT *
FROM dbo.CustomerInformation;
REVERT;
The user can retrieve customer records, but the configured columns appear masked.
To allow the user to see the original values, grant UNMASK permission:
GRANT UNMASK
ON dbo.CustomerInformation
TO SupportEmployee;
Run the query again:
EXECUTE AS USER = 'SupportEmployee';
SELECT *
FROM dbo.CustomerInformation;
REVERT;
The user can now see the original values for the applicable masking scope.
When the permission is no longer required, revoke it:
REVOKE UNMASK
ON dbo.CustomerInformation
FROM SupportEmployee;
SQL Server 2022 and later support more granular UNMASK permissions at database, schema, table, and column levels. This allows administrators to grant access to specific sensitive columns rather than exposing every masked column in a database.
Checking Existing Masking Rules
Database administrators should regularly review which columns have masking rules configured.
SQL Server provides the sys.masked_columns catalog view for this purpose.
SELECT
SCHEMA_NAME(t.schema_id) AS SchemaName,
t.name AS TableName,
c.name AS ColumnName,
c.is_masked,
c.masking_function
FROM sys.masked_columns AS c
INNER JOIN sys.tables AS t
ON c.object_id = t.object_id
WHERE c.is_masked = 1;
This query identifies masked columns, their table names, and the configured masking functions.
It is useful during security reviews, database audits, and application permission assessments.
Dynamic Data Masking vs Data Encryption
Dynamic Data Masking and encryption are different security mechanisms. They should not be treated as interchangeable.
Feature | Dynamic Data Masking | Data Encryption |
|---|
Primary purpose | Limits exposure in query results | Protects data through cryptographic techniques |
Stored data | Original value remains unchanged | Stored representation depends on encryption method |
Query behavior | Returns masked values to users without permission | Depends on encryption implementation |
Permission model | Uses SELECT and UNMASK permissions | Uses encryption keys and related permissions |
Main use case | Reducing accidental data exposure | Protecting confidentiality of sensitive information |
Dynamic Data Masking is useful when different users need different levels of visibility into the same records.
Encryption is more appropriate when the requirement is to protect the confidentiality of stored data or data processed through supported encryption mechanisms.
Dynamic Data Masking cannot be applied to a column protected using Always Encrypted. Choose the appropriate mechanism based on the application's security requirements.
Important Security Limitations
Dynamic Data Masking is not a complete security solution. Understanding its limitations is essential before using it in production.
It Does Not Encrypt Data
The original values remain in the database. A masking rule only changes what an eligible query returns to a user.
It does not protect the underlying data from database administrators or other principals with sufficient permissions.
Users May Infer Original Values
Users with permission to execute ad hoc queries may sometimes infer masked values through filtering conditions or repeated queries.
For example:
SELECT CustomerId, Salary
FROM dbo.Employees
WHERE Salary > 99999
AND Salary < 100001;
Even if the salary appears masked in the result, the filtering condition is evaluated against the underlying value.
This can reveal information about the original data.
Restrict ad hoc query access and use auditing where appropriate.
It Does Not Prevent Updates
Masking does not automatically prevent users from modifying a masked column.
A user who has UPDATE permission may still change the original value, even if the value appears masked when queried.
Use appropriate table, column, and role permissions to control write operations.
Privileged Users Can View Original Values
Users with UNMASK permission or sufficiently elevated administrative permissions can access unmasked data.
For example, SQL Server administrators and users with db_owner privileges can view original values.
Apply the principle of least privilege when assigning database roles and permissions.
Best Practices for Production Applications
Apply masking to genuinely sensitive columns such as email addresses, phone numbers, account details, and salaries.
Grant SELECT permission separately from UNMASK permission.
Use column-level UNMASK permissions when supported and appropriate.
Avoid granting UNMASK at database level unless the user genuinely needs access to all applicable masked columns.
Restrict ad hoc SQL query access for users who should not see sensitive values.
Use auditing to monitor access to sensitive data.
Apply UPDATE and DELETE permissions separately because masking does not restrict data modification.
Review administrative roles and avoid unnecessary db_owner membership.
Test masking behavior using actual application database accounts.
Use encryption when the requirement is to protect the underlying stored data.
Review masking policies whenever database schemas or application roles change.
Do not treat masked output as anonymized data suitable for every testing or analytics purpose.
Advantages and Disadvantages
Advantages
Reduces accidental exposure of sensitive information.
Allows different users to query the same records with different visibility.
Supports multiple built-in masking functions.
Can be applied to existing table columns.
Does not require changing the original stored values.
Integrates with SQL Server permissions.
Disadvantages
Does not encrypt or protect the underlying stored data.
Does not prevent authorized users from modifying masked columns.
Users with sufficient query access may infer original values.
Privileged users can view unmasked data.
Masking does not provide row-level access control.
It cannot replace a broader database security strategy.
Conclusion
Dynamic Data Masking is a useful SQL Server feature for reducing accidental exposure of sensitive information in query results. It allows database administrators to define masking rules for selected columns and control which users can retrieve the original values through UNMASK permissions.
Functions such as default, email, partial, and random masking support different data types and application requirements. Administrators can also apply or remove masking rules on existing columns and manage permissions at different database scopes.
However, Dynamic Data Masking should not be considered encryption or complete data protection. It does not change the underlying values, prevent updates, or stop every possible inference attack.
For production applications, combine Dynamic Data Masking with least-privilege permissions, auditing, appropriate access controls, and encryption where required. This provides a stronger approach to protecting sensitive SQL Server data while allowing authorized users to perform their daily work.
Join the conversation! Your thoughts help the community grow.