Data Masking, Encryption & Protecting PII in SQL Databases
Mask, encrypt, and minimize PII exposure in queries, backups, and replicas.
In plain words
Keep only the personal data you need, show most people a hidden version, and lock up the real values.
Think of it like…
A hospital's records room: most staff see only a patient's name and ward on the board, doctors can open the full file, the files are locked in a cabinet, and copies for training have the names blacked out.
Where you’ve seen it
A lending app gives support agents a view showing '******' || right(phone, 4) and the email's first two characters, while the full values are readable only by the KYC service role. PAN numbers are encrypted in the application with a key from a cloud KMS before they reach the database, a keyed hash column allows exact-match lookup, and the staging database is refreshed from a masked copy instead of a production dump.
Words you’ll hear
- Data minimisation
- Collect and keep only the personal data you need, for as long as you need it.
- Masking
- Showing a partial or replaced value (******3210) to users who don't need the original.
- Encryption at rest / in transit / column-level
- Disk and backups / network connections / individual sensitive values.
- Keyed hash (HMAC)
- A secret-keyed hash for equality lookup that can't be reversed by guessing values.
Visual diagram
Theory & example queries
Minimise, restrict and mask
Start by classifying columns (public, internal, personal, sensitive) and removing what you don't need: if you only need a user's birth year, don't store their date of birth. Set retention: delete or anonymise inactive accounts and old logs on a schedule, and support erasure requests across every table that holds the person's data.
Then limit reads. Revoke direct table access and grant roles a view that masks or omits sensitive columns, for example CREATE VIEW support_customers AS SELECT id, name, left(email, 2) || '***@' || split_part(email, '@', 2) AS email, '******' || right(phone, 4) AS phone FROM customers;. PostgreSQL also supports column-level GRANT SELECT (id, name), SQL Server has Dynamic Data Masking, Snowflake has masking policies, and PostgreSQL's anonymizer extension provides declarative masking rules.
REVOKE ALL ON customersFROM analyst_ro;GRANTSELECT (id, city, signup_date, plan) ON customers TO analyst_ro;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Expected output
Note: Representative PostgreSQL authorization flow; the permitted row count is illustrative and exact wording varies by server.
Analysts can query demographics, and any query selecting email or phone fails with permission denied.
Key takeaway: Delete what you don't need; give people views and columns, not whole tables.
Encryption, hashing and copies
Encrypt connections with TLS (clients using sslmode=verify-full), and storage and backups with disk or managed-service encryption. At-rest encryption protects stolen disks and backup files, but anyone who can run SELECT still sees plaintext. For the most sensitive values (government ids, bank details), encrypt in the application with keys held in a KMS, or use pgcrypto's pgp_sym_encrypt while keeping keys out of the database and query logs. Encrypted columns can't be searched directly, so add a keyed hash column (HMAC with a secret key) for exact-match lookups; a plain SHA-256 of a 10-digit phone number can be reversed by trying every number.
Finally, contain copies. Production dumps restored into staging, CSV exports, BI extracts, query logs with literal values and read replicas all hold PII. Build masked or synthetic datasets for development, log parameters rather than literals, restrict and audit exports, and apply the same encryption and retention to backups. For analytics, pseudonymise: replace identifiers with stable random ids and keep the mapping table locked away.
INSERT INTO kyc (user_id, pan_encrypted, pan_lookup)VALUES ($1, $2, $3);PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
SELECT user_idFROM kycWHERE pan_lookup = $1;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Expected output
Note: Illustrative insert followed by a one-row lookup for the supplied HMAC; the parameter values and status text are driver-dependent.
where the application sends $2 = AES-GCM ciphertext from a KMS-managed key and $3 = HMAC-SHA256(secret, normalised PAN). Lookup:
Key takeaway: TLS + at-rest for everything, app-level encryption + HMAC for the most sensitive, masked copies everywhere else.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Classify and minimise
List columns with personal data, drop what you don't need, and set retention for the rest.
email: personal · pan: sensitive · city: internal
When to use it & trade-offs
What it is
Protecting PII (names, emails, phone numbers, addresses, government ids) in a database combines four layers: minimise what you store and how long you keep it; restrict who can read it with column grants and masked views; encrypt it in transit (TLS), at rest (disk or backup encryption) and, for the most sensitive fields, at column level; and keep it out of logs, replicas and dev copies. Masking shows ha***@gmail.com to people who don't need the full value.
Why it matters: Breaches usually come from over-broad access, a leaked backup, a staging copy of production or an analyst's export, not from a hacker decrypting a disk. Privacy laws such as GDPR and India's DPDP Act require purpose limits, deletion on request and reasonable safeguards. Engineers are expected to design for this, and interviews for fintech, health and SaaS roles ask how.
When to reach for it
- Support and analyst access to customer tables
- Storing government ids, bank details and health data
- Refreshing staging and dev environments
When to avoid or be careful
- Copying production dumps into staging
- Relying on disk encryption to stop insiders
- Plain unsalted hashes of phone numbers or emails
Masking vs encryption vs tokenisation
Strengths: Easy to apply per role; no key management.
Watch out: The real value is still stored in plaintext.
Strengths: Stolen files are useless without keys.
Watch out: Key management; encrypted columns can't be searched or sorted directly.
Strengths: Most systems never see real PII.
Watch out: Needs a secure token vault or mapping table.
Interview signals & numbers to know
When this topic comes up
- “How would you protect customer PII?”
- “Support needs to verify a customer without seeing their full number”
- “We need GDPR / DPDP compliance”
- Encryption at rest vs column encryption
- Masking in staging
Benchmarks & rules of thumb
- 4
- layers: minimise, restrict, encrypt, contain
- 10¹⁰
- possible 10-digit phone numbers: easy to brute-force a plain hash
- verify-full
- the strict PostgreSQL TLS mode
Common mistakes & follow-ups
Common interview mistakes
- Restoring last night's production dump into staging, giving every contractor full customer data.
- Storing SHA-256(phone) as "anonymised", which anyone can reverse by hashing all possible numbers.
- Encrypting a column with pgp_sym_encrypt and passing the key as a literal, so it appears in the query logs.
Likely interviewer follow-ups
- How would you let analysts query customer data without exposing PII?
- What does encryption at rest protect against, and what doesn't it?
- How do you look up a record by an encrypted value?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Data Masking, Encryption & Protecting PII in SQL Databases with hands-on SQL practice and interview Q&A.