Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Developers need a copy of production data for testing. Write SQL that masks email addresses and phone numbers in a PostgreSQL customers table while keeping emails unique and formats valid.

We replace each email with a value built from the row's id, such as 'user' || id || '@example.test', and each phone with a fixed prefix plus digits derived from the id, so emails stay unique, formats stay valid and the same customer gets the same masked value in every table. Free-text fields such as notes and addresses must be masked too, because they often contain personal data. Better still, the masking runs in a pipeline so raw data never lands in the test environment at all, or we generate synthetic data; extensions such as PostgreSQL Anonymizer can help.

Why this question is asked

Testing against realistic data finds bugs that tidy fixtures never do, so developers keep asking for a copy of production. But a copy of production in a test environment is usually the least protected copy of customer data the company has: broad access, weak monitoring, laptops, debug logs. Privacy laws treat it the same as production data. Interviewers ask for the SQL because good masking has to keep the data useful, with unique emails, valid formats and consistent joins, while removing the person. In this answer, we will recap what masking needs to achieve, write the SQL, look at the fields people forget, see why masking in place is risky, and build a safer pipeline.

1A Quick Recap of What Masking Must Achieve

Masking replaces real personal data, called PII for personally identifiable information, with fake values that look and behave like real ones. Behave matters most. If emails have a unique constraint, masked emails must stay unique or the copy will not load. If the application validates phone formats, masked phones must pass validation. If the same customer's email appears in an orders table and a newsletter table, both must get the same masked value, so that joins and lookups in tests still work. This property is called deterministic masking: the same input always gives the same output.

2Writing the Masking SQL

The simplest deterministic source is the row's primary key, which is already unique and does not reveal anything about the person.

SQL
UPDATE customers
SET email = 'user' || id || '@example.test',
phone = '+1555' || lpad((id % 10000000)::text, 7, '0');
SELECT id, email, phone FROM customers ORDER BY id LIMIT 3;
-- 1 | user1@example.test | +15550000001
-- 2 | user2@example.test | +15550000002
-- 1042 | user1042@example.test | +15550001042
SELECT count(*), count(DISTINCT email) FROM customers; -- 250000 | 250000
-- tables that copy the email get the same value through the customer id
UPDATE newsletter_subscriptions n
SET email = 'user' || c.id || '@example.test'
FROM customers c WHERE c.id = n.customer_id;

Each choice has a reason. Building the email from the id keeps it unique because the id is unique. The domain example.test uses the .test top-level domain, which is reserved and can never receive mail, so a test environment that accidentally sends a newsletter cannot reach a real person. The phone is a valid-looking number of fixed length, produced by lpad, which pads the remainder of the id to seven digits; the remainder repeats after ten million ids, which is fine because phones are not unique. The last statement shows how tables that copy the email get exactly the same masked value by joining on the customer id, so lookups across tables still match.

3The Fields People Forget

Emails and phones are the obvious fields. The leaks usually come from the others. Names and dates of birth are personal data too. Addresses identify people, especially combined with a postcode. And free-text fields, such as support notes, delivery instructions or order comments, are the worst, because people type anything into them: phone numbers, card details, health information, the name of the neighbour who took the parcel. We cannot reliably clean free text with patterns, so we replace it.

SQL
UPDATE customers
SET first_name = 'First' || id,
last_name = 'Last' || id,
birth_date = date '1980-01-01' + (id % 15000), -- plausible but not real
street = id || ' Test Street',
notes = CASE WHEN notes IS NULL THEN NULL ELSE 'masked note ' || id END;

To find the forgotten fields systematically, we keep a list of columns classified as personal data, ideally as column comments or in a data catalog, and the masking script fails if it meets a text column that is neither masked nor marked as safe. New columns added by migrations then cannot silently carry real data into the test copy.

4Why Masking in Place Is Risky

There is a catch with running these UPDATE statements on a restored copy inside the test environment. Until the masking finishes, the test environment holds raw production data. Even after it finishes, PostgreSQL keeps the old row versions in the table files until vacuum removes them, the write-ahead log contains the old values, and any backup or snapshot taken in between contains everything. If the script fails halfway, someone may start using a half-masked database. So masking in place inside the target environment protects much less than it seems.

5A Safer Pipeline, or No Real Data at All

The better design is a pipeline that runs inside a secured zone with production-level controls. It restores a backup into an isolated, short-lived database, runs the masking, verifies the result, exports only the masked data, and destroys the temporary database. Only the masked export ever reaches the test environment.

Step throughProducing a masked copy for developers
  1. Restore backup in a secure zoneisolated, short-lived, production controls
  2. Run masking scriptsdeterministic, every classified column
  3. Verify the resultscan for real-looking emails, phones, card numbers
  4. Any real-looking values left?
    YesStop and fix the scriptNoExport masked data only
  5. Load into test environmenttemporary database is destroyed

5 steps in order. Play them, or step through them one at a time.

Raw data never leaves the secure zone.

6Tools and Synthetic Data

Writing masking SQL by hand works for a few tables. For larger schemas, the PostgreSQL Anonymizer extension, known as anon, lets us declare masking rules per column with security labels and provides functions for fake names, addresses and partial masking, either for static masked copies or dynamic masking for certain roles; check which versions of PostgreSQL and managed services support it. For many tests, synthetic data, generated by scripts or libraries from the schema with realistic distributions, is better still: it contains no person at all and can be shared freely. A common mix is synthetic data for everyday development and a masked copy for performance tests that need production-like volumes and skew.

7Follow-up questions

Why not hash the real email instead of using the id?

A plain hash of an email can be reversed by hashing a list of known emails and comparing, so it is still personal data. A keyed hash avoids that but the result is not a valid email, so we would still need to build one around it. Using the id is simpler, unique and reveals nothing.

How do you keep the masked copy consistent across several databases?

Use a deterministic rule based on a shared key, such as the customer id, in every database, or a keyed hash of the original value with a secret key held only by the pipeline. Then the same customer gets the same masked email in the orders database and the CRM database, and cross-service tests still match.

Is masked data still personal data under privacy laws?

It can be if it is possible to re-identify people, for example by combining unmasked fields such as postcode, birth date and gender. That is why we mask quasi-identifiers like dates and addresses too, and why synthetic data is the safest option.

8Conclusion

In this answer, we masked a PostgreSQL customers table by deriving emails and phones from the row id, which keeps emails unique, formats valid and values deterministic across tables, and we used the reserved .test domain so no real person can be emailed. We masked names, dates, addresses and free-text notes, and saw why masking in place leaves raw data in the target environment through old row versions, WAL and backups. A pipeline in a secure zone that exports only masked data, extensions such as anon, and synthetic data are the safer options.

What to say in the interviewAbout 90 seconds aloud

Open with

I would mask deterministically from the primary key, because it is unique and says nothing about the person. For example, UPDATE customers SET email = 'user' || id || '@example.test', phone = '+1555' || lpad((id % 10000000)::text, 7, '0').

Then, if they want more

The email stays unique, it is a valid format, and the .test domain is reserved so nothing can ever be delivered to a real person. The phone has a fixed valid-looking format.

Because it is derived from the id, the same customer gets the same masked value in every table, so I update copies like newsletter subscriptions by joining on the customer id and joins still work in tests.

I would also mask names, birth dates and addresses, and replace free-text fields like notes entirely, because people type all sorts of personal data into them. A list of classified columns makes the script fail if a new text column is not handled.

Running this in place in the test environment is risky, because raw data is there until masking finishes and old row versions, WAL and backups keep it. So I prefer a pipeline in a secure zone that restores a backup, masks, verifies, and exports only the masked data, or synthetic data for daily development.

Tools like the PostgreSQL Anonymizer extension can help, depending on the version and platform.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Developers need a copy of production data for testing. Write SQL that masks email...": https://scrivio-interview-library.netlify.app/databases/database-security/ef556b515f/