Row and Column Level Security

Earn 25 points (50 with Pro) in two steps

  1. ① Read through the lesson — each section gets a ✓ as you scroll through it.
  2. ② When every section has a ✓, tap Complete lesson.

0 of 10 read · keep scrolling

✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro

Mastering Data Access Control: Row and Column Level Security in Unity Catalog

Introduction: Why Granular Access Control Matters

In modern data architecture, the "one-size-fits-all" approach to data access is no longer sustainable. As organizations collect vast amounts of information, the responsibility to protect that data—while simultaneously making it available to those who need it—has become a primary challenge for data engineers and administrators. Unity Catalog, the unified governance solution for the Databricks Data Intelligence Platform, addresses this challenge by providing sophisticated mechanisms for controlling exactly who can see what within your data assets.

Row-level security (RLS) and column-level security (CLS) represent the next evolution of data protection. Instead of granting access to an entire table or database, these controls allow you to filter data at the record level or mask sensitive information at the attribute level based on the user's identity or role. This is critical for compliance with global privacy regulations like GDPR, HIPAA, and CCPA, where restricting access to personally identifiable information (PII) or sensitive financial records is not just a best practice, but a legal requirement.

By mastering these techniques, you move away from creating fragile, redundant views or duplicating data for different user groups. Instead, you create a single source of truth that dynamically adjusts its content based on the person querying it. This lesson will guide you through the conceptual framework, the technical implementation, and the strategic best practices for managing row and column-level security within Unity Catalog.


Not read yet

Understanding the Conceptual Framework

Before diving into the syntax, it is important to understand the difference between how we traditionally handled data security and how Unity Catalog handles it today. In the past, if a manager needed to see only their region's sales data, you might have created a separate table for that manager, or a complex series of views that were difficult to maintain. If you had 50 managers, you had 50 views or tables to manage.

Unity Catalog simplifies this by using User Defined Functions (UDFs) to enforce logic at runtime. When a user executes a SELECT statement, Unity Catalog evaluates the function against the user’s identity (using current_user() or is_account_group_member()). If the logic dictates that a row should be hidden or a column should be masked, the engine performs this transformation on the fly before the query results are returned to the user.

Callout: Static vs. Dynamic Security Static security involves physically separating data into different files or tables. While this is secure, it is operationally expensive and prone to data drift. Dynamic security, which we are discussing here, keeps the data in one location but applies logic at the time of the query. This is significantly more flexible and easier to audit, as you have one table definition to govern rather than hundreds of individual files.


Not read yet

Implementing Column-Level Security (CLS)

Column-level security allows you to mask sensitive information. For example, you might want to show a customer's email address to marketing analysts but redact it for support staff. Instead of creating two tables, you apply a mask to the email column.

How Data Masking Works

In Unity Catalog, masking is achieved by applying a function to a column. When a user queries that column, the system checks if the mask should be applied. If it is, the function transforms the value (e.g., replacing the middle of an email with asterisks) before the user sees it.

Step-by-Step Implementation

  1. Define the Masking Function: You first create a SQL function that defines how the data should be masked.
  2. Apply the Mask: You use the ALTER TABLE command to attach this function to a specific column.
  3. Grant Permissions: Ensure that the users who need to see the unmasked data have appropriate permissions, while others inherit the masked view.

Example: Masking an Email Column

Suppose we have a table named customers with a column email. We want to mask this email so that only authorized users see the full address.

-- Step 1: Create the masking function
CREATE OR REPLACE FUNCTION mask_email(email STRING)
  RETURN CASE
    WHEN is_account_group_member('data_stewards') THEN email
    ELSE '***@***.com'
  END;

-- Step 2: Apply the mask to the table
ALTER TABLE main.sales.customers 
ALTER COLUMN email SET MASK mask_email;

In this example, the mask_email function checks if the current user is a member of the 'data_stewards' group. If they are, the function returns the original email. If they are not, it returns a generic string. Because this is applied at the table level, any query, dashboard, or notebook accessing this column will respect this rule automatically.

Note: Masking functions are applied at runtime. This means that if you have a very large dataset, the function logic should be kept simple to avoid performance degradation during query execution.


Not read yet

Implementing Row-Level Security (RLS)

Row-level security is about filtering the set of rows returned by a query. This is commonly used in multi-tenant applications or regional sales reporting where a user should only see rows belonging to their specific department, region, or country.

The Logic of Row Filters

Row-level security uses a filter function that acts like a WHERE clause. When a query is run against a table, Unity Catalog implicitly appends this filter to the query. If the function returns TRUE for a row, the row is included; if it returns FALSE, it is excluded.

Step-by-Step Implementation

  1. Define the Filter Function: Create a function that returns a boolean value based on the user's identity.
  2. Apply the Filter: Use the ALTER TABLE command to attach the filter to the table.
  3. Verify: Test the filter with different user accounts to ensure the correct rows are visible.

Example: Regional Sales Filtering

We have a table sales_data with a column region. We want to ensure that managers only see rows where the region matches their assigned territory.

-- Step 1: Create the row filter function
CREATE OR REPLACE FUNCTION filter_region(region STRING)
  RETURN CASE
    WHEN is_account_group_member('admin_group') THEN TRUE
    WHEN is_account_group_member('us_sales_team') AND region = 'US' THEN TRUE
    WHEN is_account_group_member('eu_sales_team') AND region = 'EU' THEN TRUE
    ELSE FALSE
  END;

-- Step 2: Apply the filter to the table
ALTER TABLE main.sales.sales_data 
SET ROW FILTER filter_region ON (region);

In this case, when a user from the 'us_sales_team' runs SELECT * FROM sales_data, Unity Catalog effectively executes SELECT * FROM sales_data WHERE region = 'US'. The user never needs to know the filter is being applied; the system handles it transparently.

Callout: RLS vs. CLS Row-level security changes which records are visible, while column-level security changes how the data in those records is displayed. Often, you will use both in tandem. For example, a user might only see rows for their region (RLS), and within those rows, the email column might be masked (CLS).


Not read yet

Best Practices for Data Access Control

Implementing security is not just about writing code; it is about establishing a robust governance framework. Here are the industry-standard practices for managing Unity Catalog security.

1. Principle of Least Privilege

Always start by denying access to everything and then granting only the minimum access required for a user to perform their job. Do not give users SELECT access to the entire table if they only need to see specific rows or columns.

2. Use Groups, Not Individuals

Never assign permissions or row-level security logic to individual users. If a user leaves the team or changes roles, you would have to manually update your functions. Instead, assign users to groups (e.g., hr_analysts, finance_leads) and write your functions to reference those group memberships.

3. Keep Functions Simple and Performant

Since these functions execute every time a query is run, complex logic can introduce latency. Avoid performing heavy joins or lookups inside your masking or filter functions. If you need to map users to regions, consider using a lookup table or caching the user's permissions in a small, fast-access structure.

4. Consistent Naming Conventions

As your organization grows, you will end up with dozens or hundreds of masking and filter functions. Use a clear naming convention (e.g., mask_pii_email, filter_by_region_v1) to make it easy to audit which functions are being used and where.

5. Regular Auditing

Use the Unity Catalog audit logs to monitor which users are accessing which tables. If you notice a high volume of failed access attempts or unusual query patterns, it may be an indication that your security policies need adjustment or that someone is attempting unauthorized data access.


Not read yet

Common Pitfalls and How to Avoid Them

Even with a powerful tool like Unity Catalog, it is easy to make mistakes that can lead to data leaks or performance issues.

Pitfall 1: Over-Engineering the Logic

Many administrators try to pack too much business logic into the security function. For instance, they might try to perform a complex JOIN inside the security filter to determine if a user has access to a row based on a chain of relationships.

  • The Fix: Keep the security logic focused on identity and simple attribute checks. If the logic is too complex, consider creating a dedicated "security view" or pre-calculating the user's access rights in a separate table.

Pitfall 2: Forgetting about Downstream Dependencies

If you apply a row filter, it might inadvertently break downstream processes. For example, if a BI tool expects a certain number of rows and suddenly receives fewer because of a filter, it might throw an error or display inaccurate totals.

  • The Fix: Always communicate changes in security policies to data consumers. Test your filters in a staging environment before applying them to production tables.

Pitfall 3: Security through Obscurity

Some developers believe that by hiding columns, they have secured the data. However, if a user can still perform aggregations or run queries that infer the hidden data, the security is ineffective.

  • The Fix: Ensure that your security policies are holistic. If you mask an email, ensure that you also consider whether the user can infer the email address through other columns or secondary tables.

Not read yet

Comparison: Traditional Views vs. Unity Catalog Security

Feature Traditional Views Unity Catalog Security (RLS/CLS)
Management Overhead High (one view per user/group) Low (one table, dynamic rules)
Flexibility Rigid Dynamic based on User Context
Maintenance Difficult to update logic Centralized function management
Scalability Poor Excellent
Auditability Fragmented Centralized in Unity Catalog

Advanced Scenarios: Combining RLS and CLS

In complex enterprise environments, you will often find that you need to combine both RLS and CLS. Imagine a global HR database where:

  • Regional HR managers can only see employees in their region (RLS).
  • Even within their region, they cannot see the social security number (SSN) column (CLS).
  • Global HR admins can see all employees (RLS) but still cannot see the SSN column unless they have a special clearance (CLS).

This can be implemented cleanly by layering the controls. First, you define the row filter to restrict records by region. Second, you define the masking function for the SSN column. Because Unity Catalog executes these independently, the user receives a result set that is both filtered (only their region) and masked (SSN hidden).

-- Applying both to the same table
ALTER TABLE hr.employees 
SET ROW FILTER filter_region ON (region);

ALTER TABLE hr.employees 
ALTER COLUMN ssn SET MASK mask_ssn;

This modular approach allows you to update the filter_region logic without touching the mask_ssn logic, keeping your governance code clean and maintainable.


Not read yet

Troubleshooting and Debugging

If you find that a user is not seeing the data they expect, start by verifying their identity and group memberships. You can use the following commands to check what the system sees:

-- Check the current user
SELECT current_user();

-- Check if the user is in a specific group
SELECT is_account_group_member('finance_team');

If the user is in the correct group but still cannot see the data, check the definition of the masking or filtering function. You can use DESCRIBE FUNCTION to view the code within the function to ensure the logic is correct.

Warning: Be cautious when using SELECT * in your testing. If you are testing a masking policy, SELECT * might hide the column, but you should also explicitly query the masked column to ensure the output matches your expectations.


Handling Schema Evolution

One of the challenges with data governance is that schemas change. A table might get a new column, or an existing column might be renamed. When this happens, your security functions might become invalid.

Unity Catalog handles this gracefully in most cases, but you should always review your security functions whenever you perform ALTER TABLE operations. If you rename a column that is referenced in a row filter, the filter will break. Always update your filter functions before or simultaneously with renaming columns in your production tables.


Not read yet

Managing Security at Scale

As your data estate grows, managing security manually through SQL commands can become tedious. Many organizations move toward an "Infrastructure as Code" (IaC) approach for Unity Catalog security.

Automation via Terraform or Pulumi

You can manage your Unity Catalog grants, functions, and table policies using Terraform. This allows you to:

  • Version control your security policies in Git.
  • Implement peer review (Pull Requests) for any changes to security functions.
  • Automatically deploy policies across different environments (Dev, Test, Prod).

By treating security as code, you eliminate the risk of manual errors and ensure that your governance posture is consistent across the entire enterprise.


Frequently Asked Questions

Can I apply row-level security to views?

Yes, you can apply row-level security to both tables and views in Unity Catalog. However, it is generally recommended to apply it directly to the base tables to ensure that the security policy is inherited regardless of how the data is accessed.

Do these security features impact query performance?

There is a negligible overhead for executing the security functions. In almost all cases, the impact is imperceptible. However, as noted earlier, avoid complex operations like heavy joins or external API calls within your security functions to maintain optimal performance.

Can I use external data in my security functions?

No, security functions in Unity Catalog must be deterministic and self-contained within the catalog environment. You cannot call external web services or query data outside of your Unity Catalog metastore from within these functions.

What happens if a user has multiple roles?

Unity Catalog evaluates the logic provided in your function. If your function uses is_account_group_member(), it will return TRUE if the user is a member of any of the groups you specify. You can build complex conditional logic to handle overlapping roles as needed.


Not read yet

Key Takeaways

To summarize, mastering row and column-level security in Unity Catalog is essential for modern data governance. Here are the core principles to remember:

  1. Centralization: Unity Catalog provides a single point of control for security. Use it to consolidate your governance logic rather than scattering it across different views or applications.
  2. Dynamic Enforcement: Use functions to enforce security at runtime. This allows your data to remain in a single, clean state while appearing differently to different users based on their context.
  3. Group-Based Logic: Always base your security functions on group memberships rather than individual user IDs. This makes your security model sustainable and easy to manage as your organization grows.
  4. Performance Matters: Keep your masking and filtering functions lightweight. High-performance data environments require security that does not interfere with the speed of analytical queries.
  5. Audit and Monitor: Governance is an ongoing process. Regularly audit your security functions and access logs to ensure that your policies remain effective and that no unauthorized access is occurring.
  6. IaC for Scale: As you manage larger environments, move toward automating your security policy deployment using tools like Terraform to ensure consistency and traceability.
  7. Layered Security: Don't be afraid to combine row-level and column-level security. A layered approach is often the most effective way to protect sensitive data while maintaining utility for your end users.

By following these practices, you can build a secure, compliant, and highly functional data environment that empowers your teams to work with data safely and effectively. Security, when done correctly, does not hinder data access; it enables it by providing the trust and guardrails necessary for widespread data adoption.

Not read yet

Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.