Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 155/ 160
08. Transactions, Security & Production SQL Administration

Data Masking, Encryption & Protecting PII in SQL Databases

Mask, encrypt, and minimize PII exposure in queries, backups, and replicas.

AdvancedMasking · Encryption3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Column-level grantsQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1REVOKE ALL ON customers2FROM3  analyst_ro;45GRANT6SELECT7  (id, city, signup_date, plan) ON customers TO analyst_ro;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/7
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output
REVOKE GRANT Permitted SELECT: 3 rows returned SELECT email: ERROR: permission denied for table customers

Note: Representative PostgreSQL authorization flow; the permitted row count is illustrative and exact wording varies by server.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Encrypted value plus lookup hashQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1INSERT INTO2  kyc (user_id, pan_encrypted, pan_lookup)3VALUES4  ($1, $2, $3);
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/4
query.sql
1SELECT2  user_id3FROM4  kyc5WHERE6  pan_lookup = $1;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/6
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output
INSERT 0 1 user_id 42

Note: Illustrative insert followed by a one-row lookup for the supplied HMAC; the parameter values and status text are driver-dependent.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Inventory

Classify and minimise

List columns with personal data, drop what you don't need, and set retention for the rest.

Focus at this step

email: personal · pan: sensitive · city: internal

What to watch at this step
Best protection
not storing it
Tip: use ← → to move between steps

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

Masking (views, DDM, masking policies)
Best for: Letting staff work with records without seeing full values

Strengths: Easy to apply per role; no key management.

Watch out: The real value is still stored in plaintext.

Encryption (at rest, column, application-level)
Best for: Protecting stored and copied data

Strengths: Stolen files are useless without keys.

Watch out: Key management; encrypted columns can't be searched or sorted directly.

Tokenisation / pseudonymisation
Best for: Analytics and systems that only need a stable identifier

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?
Interview tip: Answer in layers: minimise, restrict, encrypt, contain copies. Most candidates stop at "encrypt it"; mentioning staging data and backups shows real-world experience.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Preventing SQL Injection (Parameterized Queries & Prepared Statements)
Next topic
Logical Backups (pg_dump, mysqldump) vs Physical Backups