# Protecting personal data in the warehouse: hashing, keyed tokens, masking and k-anonymity

Hashing an email column feels like anonymising it, but a dictionary attack reversed all 10,000 hashed rows in our test. This guide measures what hashing, keyed tokens and generalisation really protect, and shows how masking and row policies in Snowflake and Databricks fit in.

Analytics teams need personal data to do useful work: count customers, join orders to accounts, study churn by region. Privacy rules and common sense say most people who query the warehouse should not see names, emails or exact birth dates. The usual compromise is to transform the sensitive columns. Hash the email, mask the phone number, round the birth date.

Those transformations are not equal. Some protect almost nothing against a motivated reader. Some protect the identifier but leave people identifiable through the combination of ordinary columns. And some protection lives not in the data at all but in policies that decide, per query, what each user sees.

This article tests the common techniques on a synthetic table of 10,000 people in DuckDB 2.0.1 and reports what each one actually achieves. The table has an email, a five-character postcode, a birth year, a gender and a health-style category, which is the kind of data that turns up in real warehouses. The code is short enough to rerun on your own data.

## What happened

### EDPB adopts Guidelines 01/2025 on pseudonymisation for consultation (16 January 2025)

The European Data Protection Board adopted its Guidelines 01/2025 on pseudonymisation on 16 January 2025 and published them for public consultation, which drew written comments from organisations and researchers. The guidelines describe pseudonymisation as a safeguard under the GDPR, not as anonymisation: pseudonymised data remains personal data, because someone holding the additional information can re-link it. That framing is the reason to measure, as this article does, how easily the link can be rebuilt.

### DuckDB 2.0.1 is released (20 November 2026)

DuckDB 2.0.1 was published on PyPI on 20 November 2026. It is the engine used for every measurement below.

## Three layers of protection

It helps to separate three questions:

| Layer | Question | Techniques |
|---|---|---|
| Identifiers | Can someone recover who a row belongs to from its key columns? | Hashing, keyed hashing (HMAC), tokenisation, encryption |
| Quasi-identifiers | Can someone single a person out from ordinary columns combined? | Generalisation, suppression, k-anonymity, l-diversity |
| Access | Who sees which rows and columns, and in what form? | Column masking policies, row access policies, views, grants |

Think of a filing cabinet. The first layer is whether the name labels on the folders are readable. The second is whether you can tell whose folder it is from what is inside, even with the label removed. The third is who has the key to which drawer.

## Identifiers: why a plain hash is not enough

The most common shortcut is `sha256(email)`. It looks random, it is consistent (the same email always gives the same hash, so joins still work) and it cannot be "decrypted". The problem is that it does not need to be decrypted. Emails are guessable, so an attacker can hash candidates and look for matches.

In the test table, emails follow a common pattern: first name, dot, last name, a number from 1 to 99, at a company domain. With 10 first names and 10 last names, the full candidate list has 10 × 10 × 99 = 9,900 addresses.

```sql
create table pseudo as
select id, sha256(email) as email_hash, zip, birth_year, gender, diag
from people;

-- attacker: hash every candidate address and join
select count(*)
from pseudo p
join candidates d on p.email_hash = sha256(d.email);
```

The join matched all 10,000 rows. Every "pseudonymised" row was re-identified with a single join. Real email spaces are larger, but leaked address lists, customer exports and predictable formats make the same attack practical. Hashing phone numbers is worse, because the space of valid numbers in a country is small enough to enumerate.

### Keyed tokens

The fix is to add a secret the attacker does not have. A keyed hash, HMAC-SHA256 with a key held in a secrets manager, keeps the useful properties of a hash (deterministic, joinable) but makes the dictionary attack useless without the key.

```python
import hmac, hashlib, duckdb

KEY = b"secret-key-held-in-a-vault"   # load from a secrets manager, never from code

def token(email: str) -> str:
    return hmac.new(KEY, email.encode(), hashlib.sha256).hexdigest()

con = duckdb.connect()
con.create_function("hmac_token", token, ["VARCHAR"], "VARCHAR")
con.execute("create table pseudo2 as select id, hmac_token(email) as email_token from people")
```

The same dictionary join against `pseudo2` matched 0 rows. The table had 6,283 distinct emails and produced exactly 6,283 distinct tokens, so joins and distinct counts still work. Store the key in a system such as [HashiCorp Vault](/tools/hashicorp-vault), rotate it with a plan (rotation changes every token), and keep the tokenising service separate from the people who query the output.

| Technique | Joinable | Reversible | Dictionary attack | Typical use |
|---|---|---|---|---|
| Plain hash (SHA-256) | Yes | No, but guessable | Succeeded on 10,000 of 10,000 rows in the test | Avoid for personal identifiers |
| Keyed hash (HMAC) | Yes, with the same key | No | Failed (0 matches) without the key | Analytics join keys |
| Vault tokenisation | Yes, through a lookup table | Yes, for authorised services | Not applicable | Payment and contact data that must be recovered |
| Encryption | Only after decryption | Yes, with the key | Not applicable | Storage and transfer protection |

The [data tokenisation page](/tools/data-tokenization) and the [Spark UDF de-identification page](/tools/spark-udf-de-identification) cover how to run these transforms at pipeline scale.

## Quasi-identifiers: measuring k-anonymity

Removing the email does not make a row anonymous. Postcode, birth year and gender are each harmless alone, but together they often point to one person. The standard measure is k-anonymity: a table is k-anonymous for a set of quasi-identifier columns if every combination of their values is shared by at least k rows. If k is 1, at least one person is unique and can be singled out by anyone who knows those three facts about them.

Measuring it is one `group by`:

```sql
select min(n)                                as k,
       sum(case when n = 1 then n else 0 end) as unique_people,
       sum(case when n < 5 then n else 0 end) as people_in_classes_below_5,
       count(*)                              as classes
from (select count(*) as n
      from people
      group by zip, birth_year, gender);
```

The results on the test table:

| Quasi-identifiers | k (smallest class) | People unique | People in classes under 5 | Classes |
|---|---|---|---|---|
| Full postcode, birth year, gender | 1 | 9,043 | 10,000 | 9,511 |
| First 3 postcode characters, birth decade, gender | 44 | 0 | 0 | 108 |
| First 2 postcode characters, birth decade, gender | 163 | 0 | 0 | 36 |
| First 2 postcode characters, birth decade | 354 | 0 | 0 | 18 |

With the raw columns, 9,043 of 10,000 people were unique, about 90%. Generalising the postcode to three characters and the birth year to a decade raised k from 1 to 44. Each extra step raises k but removes detail: the last row has only 18 groups left, which may be too coarse for a regional analysis. That trade-off, privacy against usefulness, is the whole game, and the right point depends on who will see the data.

### k-anonymity is not the end

A group of 163 people who all share the same sensitive value still leaks that value. If every person in a class has the same diagnosis, knowing someone is in the class tells you their diagnosis. l-diversity adds a second check: each class must contain at least l distinct sensitive values.

```sql
select min(d) as l
from (select count(distinct diag) as d
      from people
      group by left(zip, 2), birth_year // 10, gender);
```

For the 36-class version, every class had at least 4 of the 5 categories, so l is 4. Real data is less uniform; rare values cluster, and a check like this catches it before release. Both measures assume you chose the right quasi-identifiers. If an attacker knows something you did not list, such as a precise visit date, the guarantee does not cover it.

## Access: masking and row policies

The first two layers change the data. The third leaves the data intact and controls what each query returns. This is how most warehouses protect personal data for internal users, because the same table can serve the fraud team (who need raw emails) and the marketing analyst (who does not).

### Snowflake: masking and row access policies

In Snowflake, a masking policy is a schema object that rewrites a column at query time, depending on context such as the active role:

```sql
create masking policy email_mask as (val string) returns string ->
  case
    when is_role_in_session('PII_READER') then val
    else regexp_replace(val, '.+@', '*****@')
  end;

alter table customers modify column email set masking policy email_mask;
```

A row access policy returns a boolean per row:

```sql
create row access policy region_policy as (region varchar) returns boolean ->
  exists (select 1 from governance.region_map m
          where m.role_name = current_role() and m.region = region);

alter table sales add row access policy region_policy on (region);
```

The masking expression above was tested in DuckDB with the role passed as a parameter: `ayse.kaya12@example.com` becomes `*****@example.com` for an analyst and stays unchanged for a reader with the right role. Keeping the domain is a deliberate choice; it lets analysts count customers by email provider without seeing the person.

### Databricks Unity Catalog: row filters and column masks

Databricks uses SQL functions attached to tables:

```sql
create function governance.email_mask(email string)
  return case when is_account_group_member('pii_readers') then email
              else regexp_replace(email, '.+@', '*****@') end;

alter table main.crm.customers alter column email set mask governance.email_mask;

create function governance.region_filter(region string)
  return is_account_group_member('admins') or region = 'EU';

alter table main.sales.orders set row filter governance.region_filter on (region);
```

Databricks has announced general availability of attribute-based access control (ABAC) row filtering and column masking policies, governed tags and data classification in Unity Catalog. With ABAC, the same functions can be applied through policies that match governed tags such as "pii", so a newly tagged column is protected without a per-table `alter`. The [Unity Catalog article](/articles/databricks-unity-catalog-privileges-explained) explains the privilege model these policies build on.

| Control | Where it acts | Changes stored data | Best for |
|---|---|---|---|
| Keyed tokens | Pipeline, before storage | Yes | Shared datasets, exports, data leaving the platform |
| Generalisation | Pipeline or release step | Yes | Data published to wide audiences or partners |
| Column masking policy | Query time | No | Internal users with different needs on one table |
| Row access policy or row filter | Query time | No | Regional, tenant or team separation |

Query-time controls only protect data that stays inside the platform. As soon as someone exports a result, copies it to a spreadsheet or pastes it into an AI tool, the policy no longer applies; the [shadow AI data leaks article](/articles/llmjacking-and-shadow-ai-data-leaks) describes that path.

## What it means in practice

Plain hashing should be treated as no protection for guessable identifiers. In the test it took one join to reverse every row. Keyed tokens keep the analytic value and close that hole, as long as the key is managed like any other secret.

Removing identifiers is also not enough, because ordinary columns combine into fingerprints. A `group by` on the quasi-identifiers takes seconds and tells you how many people are unique; in the test it was 90% before generalisation and 0% after. That number belongs in the review of every dataset that leaves the core team.

Finally, policies at query time are the practical default for internal analytics. They keep one copy of the data, adapt to each user's role and are auditable. They work best together with a [data catalog](/tools/data-catalog) that tags sensitive columns, and [data lineage](/tools/data-lineage) that shows where those columns flow downstream. Legal requirements, such as those in the [GDPR](/tools/gdpr), set the goal; these techniques are how you meet it and show you met it.

## What to do now

1. **Find hashed identifiers.** Search schemas for columns named like `email_hash` or `phone_sha` and check whether they were produced without a key.
2. **Replace plain hashes with keyed tokens.** Use HMAC with a key from a secrets manager and plan how you will rotate it.
3. **Tag sensitive columns.** Mark personal and sensitive columns in your catalog so policies and reviews can find them.
4. **Apply masking by default.** Attach masking policies to tagged columns and grant unmasked access to named roles only.
5. **Add row policies for separation.** Use row access policies or row filters for regional, tenant or team boundaries instead of copying tables.
6. **Measure k before sharing.** Run the k-anonymity query on the quasi-identifiers of every dataset leaving the platform, and set a minimum k.
7. **Check l-diversity for sensitive fields.** Confirm each equivalence class holds several distinct sensitive values.
8. **Test as a low-privilege user.** Query protected tables with an analyst role and confirm masks and filters apply, including through views.
9. **Log and review access.** Record who reads unmasked data and review it regularly.

## Risks and open questions

**Pseudonymised data is still personal data.** Keyed tokens reduce risk, but whoever holds the key can re-link; legal obligations still apply.

**Quasi-identifier lists are guesses.** k-anonymity only protects against the columns you counted; external data can add new ones.

**Generalisation costs accuracy.** Coarser postcodes and age bands can hide real patterns; measure what analyses still work before release.

**Policies stop at the platform edge.** Exports, extracts and copies leave masking and row policies behind.

**Policy logic can be bypassed by mistakes.** A view owned by a privileged role, or a function with a bug, can expose data that the base policy hides; test through every access path.

**Watch next:** how tag-based policies (ABAC) spread across warehouses, how the EDPB's final pseudonymisation guidance is applied in audits, and whether privacy measures like k-anonymity become standard checks in data contracts.

## Frequently asked questions

### Is a SHA-256 hash of an email anonymous?

No. Anyone can hash a list of likely emails and match the results, which re-identified all 10,000 rows in the test. Under the GDPR it would at best be pseudonymised data, which is still personal data.

### What is the difference between hashing and tokenisation?

Hashing computes a value from the input with a public algorithm, so guessable inputs can be matched. A keyed hash adds a secret, and vault tokenisation replaces the value with a random token stored in a lookup table that only authorised services can reverse. Both keep joins working while blocking dictionary attacks.

### How do I calculate k-anonymity in SQL?

Group the table by the quasi-identifier columns, count rows per group and take the minimum count. That minimum is k. Also count how many people are in groups smaller than your threshold, because a single small group can matter.

### Should I mask data or remove it?

Mask at query time when the same table serves users with different needs, because one copy stays correct and access can change by role. Remove or generalise data when it leaves the platform or goes to wide audiences, because query-time policies do not follow exports.

### Do masking policies slow queries down?

They add an expression per protected column or a filter per row, evaluated at query time. Simple expressions like the email mask cost little; row policies that look up mapping tables add a join, so keep mapping tables small and test performance on large tables.

## Summary

Protecting personal data in a warehouse has three layers: identifiers, quasi-identifiers and access. Tests on 10,000 synthetic rows in DuckDB 2.0.1 show the gaps between them. A plain SHA-256 hash of emails was reversed for every row by a 9,900-entry dictionary, while an HMAC keyed token resisted the same attack and kept joins working. With raw postcode, birth year and gender, 90% of people were unique; generalising to a three-character postcode and a birth decade raised k from 1 to 44. Query-time masking and row policies in Snowflake and Databricks then control what each role sees. Use keyed tokens, measure k and l before sharing, and apply policies by tag.

## Sources

- [EDPB: Guidelines 01/2025 on Pseudonymisation, version for public consultation](https://www.edpb.europa.eu/system/files/2025-01/edpb_guidelines_202501_pseudonymisation_en.pdf)
- [European Law Blog: The EDPB 01/2025 Guidelines on Pseudonymisation, a step in the right direction?](https://europeanlawblog.eu/tfef074h/)
- [Databricks: ABAC row filtering and column masking policies, governed tags and data classification are now generally available in Unity Catalog](https://www.databricks.com/blog/abac-row-filtering-and-column-masking-policies-governed-tags-and-data-classification-are-now)
- [Databricks Docs: Row filters and column masks](https://docs.databricks.com/aws/en/data-governance/unity-catalog/filters-and-masks/)
- [Databricks Docs: Common patterns for row filtering and column masking](https://docs.databricks.com/aws/en/data-governance/unity-catalog/abac/common-patterns)
- [Snowflake Docs: Understanding Column-level Security](https://docs.snowflake.com/en/user-guide/security-column-intro)
- [Snowflake Docs: Understanding row access policies](https://docs.snowflake.com/en/user-guide/security-row-intro)
- [PyPI: duckdb](https://pypi.org/project/duckdb/)
