Production databases contain information that development and testing teams need to reproduce real application behavior. Customer records, orders, payment history, addresses, account settings, and transaction details help developers understand how an application behaves with realistic data.
However, copying production data directly into development or testing environments creates a serious privacy risk. Those environments may have weaker access controls, more developers with database access, additional debugging tools, and less strict data retention policies. A database backup that is safe inside a restricted production environment may expose customer information when restored onto a developer's laptop or a shared test server.
The solution is not necessarily to avoid production data completely. Teams can create realistic test datasets by masking sensitive information, replacing identifiable values, removing unnecessary records, or generating synthetic data.
PostgreSQL provides several built-in capabilities that help with this process, including SQL transformations, views, table constraints, and dump-and-restore tools. Additional masking extensions and dedicated data-generation tools can also be useful.
This article explains how to copy PostgreSQL production data into a testing environment while reducing the risk of exposing customer information. It covers data masking, referential integrity, repeatable transformations, and practical safeguards for production-to-test workflows.
Why Copying Production Data Creates a Privacy Risk
Consider an application that stores customer information in a customers table.
CREATE TABLE customers (
id BIGINT PRIMARY KEY,
full_name VARCHAR(200),
email VARCHAR(250),
phone_number VARCHAR(30),
date_of_birth DATE,
address TEXT,
created_at TIMESTAMPTZ
);
The production table may contain thousands or millions of customer records. Developers may need these records to test search functionality, customer profiles, reporting, and application workflows.
A direct copy would preserve the original information.
SELECT *
FROM customers;
If this data is restored into a shared testing database, developers and test automation systems may gain access to real customer details.
The risk is not limited to obvious fields such as names and email addresses. Several other fields can reveal someone's identity when combined.
For example:
Date of birth combined with a postal code.
Transaction history combined with an account identifier.
Delivery addresses combined with order information.
Free-text support messages containing personal details.
IP addresses and device identifiers stored in application logs.
Removing a customer's name does not automatically make a record anonymous. Other attributes may still identify the individual.
A safe testing dataset should preserve the relationships and data patterns required by the application while removing or transforming information that could expose real customers.
Choosing the Right Data Protection Strategy
There is no single masking technique that works for every application. The correct approach depends on the type of data, testing requirements, and privacy obligations.
Three common strategies are useful.
Strategy | How it works | Suitable scenario |
|---|
Data masking | Replaces sensitive values with artificial values | Testing with realistic table relationships |
Data anonymization | Transforms or removes information so individuals cannot reasonably be identified | Sharing datasets for broader analysis |
Synthetic data | Generates entirely artificial records | Testing without requiring production customer details |
Data masking is often the most practical option when developers need realistic application behavior. For example, an application may need customers, orders, and payments to remain connected through foreign keys.
Synthetic data is useful when production records are unnecessary. A test environment can generate customers with artificial names, addresses, and transaction histories.
Anonymization requires more careful consideration. Removing direct identifiers is not enough if other fields allow individuals to be identified. The organization must evaluate the complete dataset and the possibility of linking it with external information.
In many projects, a combination of these strategies provides the best result.
Identifying Sensitive Columns Before Exporting Data
Before creating a testing copy, identify which tables and columns contain sensitive information.
Start by reviewing the database schema.
SELECT
table_schema,
table_name,
column_name,
data_type
FROM information_schema.columns
WHERE table_schema = 'public'
ORDER BY table_name, ordinal_position;
This query provides a list of columns that can be reviewed during the data classification process.
Create a data inventory that identifies fields requiring protection.
For example:
Table | Column | Classification | Test strategy |
|---|
customers | full_name | Personal information | Replace with generated name |
customers | email | Personal information | Generate test email |
customers | phone_number | Personal information | Generate artificial number |
customers | date_of_birth | Potentially identifying | Shift or generalize |
customers | address | Personal information | Replace with artificial address |
payments | card_reference | Financial identifier | Replace with test reference |
orders | total_amount | Business data | Preserve if required |
The classification should include more than columns with obvious names. Review JSON fields, free-text columns, audit tables, logs, and archived records.
It is also important to identify fields that must remain consistent across tables. A customer identifier used in orders, payments, and support tickets should not be changed independently in each table.
Creating a Masked Dataset With SQL
One straightforward approach is to create a separate testing database and populate it with transformed data.
For example, suppose the production customers table contains real customer information. The testing copy should preserve the customer IDs required by related tables but replace names, email addresses, phone numbers, and addresses.
A transformation query can generate artificial values.
INSERT INTO customers_test (
id,
full_name,
email,
phone_number,
date_of_birth,
address,
created_at
)
SELECT
id,
'Test Customer ' || id,
'customer' || id || '@example.test',
'0000000000',
DATE '1990-01-01',
'Test Address ' || id,
created_at
FROM customers;
This example preserves the original customer IDs and creation timestamps while replacing several personal fields.
The example is intentionally simple. A production masking process should use values that match the application's validation rules and required data formats.
For example, replacing every phone number with the same value may cause unique-constraint violations. Similarly, using a fixed date of birth may not be suitable when the application tests age-based functionality.
A better approach is to generate deterministic artificial values based on a stable identifier.
SELECT
id,
'Test Customer ' || id AS full_name,
'customer' || id || '@example.test' AS email,
'000000' || LPAD(id::TEXT, 4, '0') AS phone_number
FROM customers;
The resulting values remain predictable for the same customer ID. This is useful when several tables or test processes need to refer to the same masked customer.
However, ensure that generated values satisfy the target column's length, format, and uniqueness constraints.
Preserving Relationships Between Tables
One of the most common problems with data masking is breaking relationships between tables.
Consider a simple application schema:
CREATE TABLE customers (
id BIGINT PRIMARY KEY,
full_name VARCHAR(200),
email VARCHAR(250)
);
CREATE TABLE orders (
id BIGINT PRIMARY KEY,
customer_id BIGINT REFERENCES customers(id),
order_date TIMESTAMPTZ,
total_amount NUMERIC(12, 2)
);
CREATE TABLE payments (
id BIGINT PRIMARY KEY,
order_id BIGINT REFERENCES orders(id),
payment_reference VARCHAR(100),
payment_status VARCHAR(30)
);
The relationships are important for testing.
If customer IDs are changed while masking the customers table, the orders table must receive the corresponding changes. The payments table must also retain its relationship with orders.
One safe strategy is to preserve internal primary keys while masking direct customer identifiers.
For example:
Keep customers.id unchanged.
Replace customers.full_name.
Replace customers.email.
Keep orders.customer_id unchanged.
Replace payment references if they contain real external identifiers.
This preserves foreign-key relationships without exposing the original customer names and contact details.
If internal identifiers themselves are sensitive or externally meaningful, create a consistent mapping table and apply the same mapping to every related table.
For example:
CREATE TEMP TABLE customer_id_mapping AS
SELECT
id AS original_id,
ROW_NUMBER() OVER (ORDER BY id) AS test_id
FROM customers;
The mapping can then be used when creating the testing copy of each related table.
SELECT
m.test_id AS id,
'Test Customer ' || m.test_id AS full_name,
'customer' || m.test_id || '@example.test' AS email
FROM customers c
JOIN customer_id_mapping m
ON m.original_id = c.id;
Apply the same mapping to orders and other related tables.
Keep the mapping inside the restricted transformation process. Do not include the original-to-test mapping in the exported testing dataset, because it could allow someone to reconnect artificial records with real customers.
Creating a Masked Copy With pg_dump and pg_restore
PostgreSQL provides pg_dump and pg_restore for creating and restoring database backups.
A normal database dump contains the original values. Therefore, simply restoring a production dump into a test environment does not protect customer information.
A safer workflow is to create a restricted staging database, transform the data there, and export only the masked result.
For example, create a staging database:
CREATE DATABASE masked_staging;
Restore the required production backup into this restricted environment using pg_restore when the backup is in custom format.
pg_restore \
--host=staging-db \
--username=restore_user \
--dbname=masked_staging \
production_backup.dump
Apply the masking transformations inside the staging database.
For example, update customer details.
UPDATE customers
SET
full_name = 'Test Customer ' || id,
email = 'customer' || id || '@example.test',
phone_number = '0000000000',
address = 'Test Address ' || id;
After verifying that the transformation is complete, export the masked database.
pg_dump \
--host=staging-db \
--username=backup_user \
--dbname=masked_staging \
--format=custom \
--file=masked_testing.dump
Restore the masked dump into the testing environment.
pg_restore \
--host=test-db \
--username=test_user \
--dbname=application_test \
masked_testing.dump
The staging database must remain restricted because it contains the original production data before masking.
Delete or securely dispose of the staging copy and intermediate backup files according to the organization's data-retention policy once the masked export has been verified.
For large databases, this process can be automated through a controlled pipeline with separate permissions for restoring production backups, applying transformations, and publishing masked test data.
Using Transactional Masking Scripts
For smaller databases or controlled staging environments, SQL transformations can be executed inside a transaction.
BEGIN;
UPDATE customers
SET
full_name = 'Test Customer ' || id,
email = 'customer' || id || '@example.test',
phone_number = '0000000000';
UPDATE payments
SET
payment_reference = 'TEST-PAYMENT-' || id;
COMMIT;
A transaction makes it possible to commit the changes together or roll them back if the transformation fails.
For a large production-sized staging database, a single large transaction may create significant WAL activity, retain old row versions, and increase storage requirements. Consider batching transformations when necessary.
Also remember that UPDATE statements can fire triggers. If the database contains triggers that send external notifications, update audit records, or perform other side effects, review their behavior before executing masking scripts.
The masking process should be designed for the staging environment rather than run directly against the live production database.
Handling Free-Text Fields and JSON Data
Structured columns are relatively easy to identify and transform. Free-text fields are more difficult.
Consider a support ticket table:
CREATE TABLE support_tickets (
id BIGINT PRIMARY KEY,
customer_id BIGINT,
subject TEXT,
description TEXT,
metadata JSONB
);
The description may contain customer names, email addresses, account numbers, or other details entered by users.
Replacing only the customer name column does not protect information stored in support ticket descriptions.
A simple testing strategy is to replace the complete description.
UPDATE support_tickets
SET description = 'Sample support request ' || id;
JSON fields need similar attention.
For example, a metadata document may contain an email address.
{
"source": "mobile",
"customerEmail": "[email protected]",
"deviceType": "Android"
}
A transformation can replace the sensitive JSON value.
UPDATE support_tickets
SET metadata = jsonb_set(
metadata,
'{customerEmail}',
to_jsonb('[email protected]'::TEXT),
false
)
WHERE metadata ? 'customerEmail';
This example handles one known JSON property. Real applications may store sensitive information at multiple nesting levels or use different property names.
Review JSON structures, logs, comments, attachments, and imported documents separately. If the application stores images or files in external object storage, database masking alone will not protect those resources.
Using Data Masking Extensions
For complex databases, maintaining large collections of custom SQL transformation scripts can become difficult.
PostgreSQL supports extensions that provide additional functionality. One option is the PostgreSQL Anonymizer extension, commonly known as pg_anonymize.
It provides mechanisms for declaring masking rules and generating anonymized data.
Depending on the selected masking approach, developers can define transformations for sensitive columns and use the extension's supported functions and policies to produce protected datasets.
For example, a masking rule may replace a real customer email address with a generated value while preserving a valid email format.
Before adopting any extension, verify its compatibility with the target PostgreSQL version, deployment platform, and security requirements. Review its installation process, permissions, and operational limitations.
An extension does not automatically guarantee that a dataset is anonymous. The team remains responsible for identifying sensitive fields, selecting suitable transformations, and validating the exported result.
Protecting the Testing Environment
Masking the data is only one part of the process. The environment receiving the dataset must also be protected.
A testing database should not have unnecessary access to production systems.
Consider the following safeguards:
Use separate database credentials for development, testing, and production.
Restrict network access to testing database servers.
Do not reuse production passwords or API credentials.
Disable or redirect external email, SMS, and payment integrations.
Avoid copying production access tokens and session identifiers.
Apply retention policies to test backups and exported datasets.
Restrict access to masking scripts and temporary staging databases.
Also review application configuration after restoring the database. A test application should not accidentally send real customer notifications or initiate live payment requests.
For example, a payment integration should use a test environment with artificial payment references rather than production credentials.
The same principle applies to background workers, webhook handlers, and scheduled jobs.
Automating the Production-to-Test Data Workflow
Manual masking is difficult to maintain when developers need fresh testing data regularly.
A better approach is to create a repeatable workflow.
The pipeline can perform the following operations:
Create a restricted staging environment.
Restore the required production backup.
Apply approved masking transformations.
Validate foreign keys, unique constraints, and required application fields.
Run automated privacy checks.
Export the masked database.
Restore the result into the testing environment.
Remove temporary staging data and intermediate files.
The pipeline should fail if a transformation does not complete or a validation check detects an unexpected result.
For example, the team can verify that no production email addresses remain in the masked customer table.
SELECT COUNT(*)
FROM customers
WHERE email NOT LIKE '%@example.test';
This is a simple example for a dataset where all customer emails are expected to use the example.test domain. A real validation process should include every relevant table and field.
Also check foreign-key relationships.
SELECT COUNT(*)
FROM orders o
LEFT JOIN customers c
ON c.id = o.customer_id
WHERE c.id IS NULL;
The result should be zero when every order must reference an existing customer.
Validation should also examine whether artificial values are unique where required, whether application constraints are satisfied, and whether sensitive values remain in less obvious columns.
Common Mistakes to Avoid
One common mistake is removing names and email addresses while leaving other identifying information untouched. Addresses, dates, transaction details, and free-text fields can still expose individuals.
Another mistake is generating random identifiers independently for each table. This can break foreign-key relationships and make the testing database unusable.
Developers should also avoid using the same artificial email address or phone number for every customer when the application expects unique values.
Do not assume that masking a database automatically protects related files, application logs, external storage, or backup archives.
Finally, avoid running a masking script directly against production without a carefully reviewed operational reason. Transformation failures, triggers, large transactions, and accidental updates can affect live application behavior.
Summary
Copying production PostgreSQL data into a testing environment can help developers reproduce realistic application behavior, but directly restoring an unmodified production backup creates unnecessary privacy risks.
A safer process identifies sensitive fields, applies suitable masking or anonymization transformations, preserves relationships between related tables, and exports only the verified protected dataset.
PostgreSQL SQL transformations, pg_dump, pg_restore, and suitable masking extensions can support this workflow. For larger systems, automate the process so every testing dataset follows the same approved steps.
The most important principle is that removing obvious identifiers does not automatically make customer data safe. Review the complete dataset, including JSON fields, free-text content, external files, and related records. Combine data protection with access controls, validation, and secure disposal of temporary copies.
A repeatable production-to-test data workflow allows development teams to work with realistic datasets while reducing the chance of exposing customer information outside the production environment.
Join the conversation! Your thoughts help the community grow.