Protecting Sensitive Data
Protecting sensitive data means making sure that personal and financial information in a database can be seen only by the people who need it, and is useless to anyone who steals it. Sensitive data includes names, emails, phone numbers, addresses, dates of birth, payment details and passwords. Laws such as the California Consumer Privacy Act (CCPA) and industry rules such as PCI DSS for card payments set requirements, and a single leak can cost a business its customers' trust. In this lesson, we will decide what not to store, see why passwords must be hashed by the application with a slow algorithm, look at encryption in transit and at rest, mask data with a view, and keep an audit trail.
In One Minute
- Store less: data you never collect can't leak. Keep only what you need, and delete it when you're done.
- Passwords: store a slow, salted hash (bcrypt, scrypt or Argon2) made in the application, never the password.
- Card numbers: don't store them; let a payment provider keep them and store only a token and the last four digits.
- Encrypt connections (TLS) and disks; restrict who holds the keys.
- Mask sensitive columns in views, and audit changes to important tables.
What Not to Store
| Data | Recommendation |
|---|---|
| Passwords | Never store them; store a slow, salted hash |
| Full card numbers, security codes | Don't store them; a payment provider keeps them and gives you a token |
| Social Security numbers | Only if the law requires it, encrypted, with very limited access |
| Dates of birth, addresses | Only if the service needs them |
| Old records of former students | Delete or anonymize after a set retention period |
The receipts in JSON in SQL follow this rule: they keep a card's brand and last four digits, never the card number.
Passwords: Hash in the Application
A password hash is a one-way fingerprint of a password. The login check hashes what the user typed and compares fingerprints, so the database never holds the password itself. But a fast hash such as SHA-256 is the wrong tool:
SELECT 'srihitha' AS user_name,
encode(sha256(convert_to('summer2025', 'UTF8')), 'hex') AS sha256_of_password
UNION ALL
SELECT 'navika',
encode(sha256(convert_to('summer2025', 'UTF8')), 'hex')
ORDER BY user_name; user_name | sha256_of_password
-----------+------------------------------------------------------------------
navika | 48a666f835501ab81b1d69e762d7c388cca40a4e597975e5515eec9122d3e1d9
srihitha | 48a666f835501ab81b1d69e762d7c388cca40a4e597975e5515eec9122d3e1d9
(2 rows)Explanation: Two users with the same password get the identical hash, so anyone who reads the table learns they share a password. Worse, SHA-256 is designed to be fast, so an attacker with a stolen table can test billions of common passwords per second. Password hashing algorithms fix both problems: they add a random salt per user, so equal passwords give different hashes, and they're deliberately slow.
| Do | Don't |
|---|---|
| Hash with Argon2id, bcrypt or scrypt in the application's language | Store passwords, or encrypt them so they can be decrypted |
Store the whole result string (it includes the salt and settings) in a column like password_hash TEXT | Use MD5, SHA-1 or plain SHA-256 for passwords |
| Hash before the password reaches the database | Send passwords into SQL, where they can appear in logs |
Encryption in Transit and at Rest
In transit means data moving between the program and the database. Use TLS, so nobody on the network can read or change it. Most drivers take a setting such as sslmode=verify-full (PostgreSQL), which both encrypts the connection and checks the server's certificate. Managed databases (Database Hosting) usually require TLS.
At rest means data stored on disk, including backups. Cloud databases encrypt storage with keys from a key management service. SQL Server and Oracle offer Transparent Data Encryption (TDE); PostgreSQL relies on disk or file-system encryption. At-rest encryption protects against stolen disks and backup files, not against someone who can log in and run SELECT.
Column encryption protects especially sensitive fields even from people who can query the table. It can be done in the application before saving, or with extensions such as pgcrypto on a PostgreSQL server. The hard part is the keys: if the key sits next to the data, encryption adds little.
Masking Data with a View
A masking view shows partly hidden values to people who don't need the full ones. Combined with privileges, support staff can see enough to help a student without seeing their full contact details:
CREATE VIEW students_masked AS
SELECT student_id,
first_name,
regexp_replace(email, '^(.).*(@.*)$', '\1***\2') AS email,
overlay(phone PLACING '***-****' FROM 7) AS phone,
city, state
FROM students;
CREATE ROLE support NOLOGIN;
GRANT SELECT ON students_masked TO support;
SET ROLE support;
SELECT * FROM students_masked ORDER BY student_id;
SELECT email FROM students ORDER BY student_id;
RESET ROLE;CREATE VIEW
CREATE ROLE
GRANT
SET
student_id | first_name | email | phone | city | state
------------+------------+------------------+----------------+---------------+-------
101 | Srihitha | s***@example.com | (415) ***-**** | San Francisco | CA
102 | Advitha | NULL | (415) ***-**** | San Francisco | CA
103 | Navika | NULL | NULL | Dallas | TX
(3 rows)
ERROR: permission denied for table students
RESETExplanation: regexp_replace keeps the first letter and the domain of an email; overlay replaces the last part of a phone number. support can read the view, which runs with its owner's rights, but not the students table itself. NULL emails and phones stay NULL.
Auditing
An audit trail records who did what, and when. For changes, a trigger can log every insert, update and delete, as Triggers showed, including current_user:
CREATE TABLE student_audit (
audit_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
changed_by TEXT NOT NULL DEFAULT current_user,
action TEXT NOT NULL,
student_id INTEGER NOT NULL,
detail TEXT
);
CREATE FUNCTION log_student_change() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO student_audit (action, student_id, detail)
VALUES (TG_OP, NEW.student_id,
'phone ' || COALESCE(OLD.phone, 'NULL') || ' -> ' || COALESCE(NEW.phone, 'NULL'));
RETURN NULL;
END;
$$;
CREATE TRIGGER students_audit
AFTER UPDATE OF phone ON students
FOR EACH ROW EXECUTE FUNCTION log_student_change();
UPDATE students SET phone = '(214) 555-0163' WHERE student_id = 103;
SELECT changed_by, action, student_id, detail FROM student_audit;CREATE TABLE
CREATE FUNCTION
CREATE TRIGGER
UPDATE 1
changed_by | action | student_id | detail
------------+--------+------------+------------------------------
postgres | UPDATE | 103 | phone NULL -> (214) 555-0163
(1 row)Explanation: The log records the database user who made the change and what changed. Triggers can't see SELECTs, so auditing who read data needs the database's audit features instead, such as the pgaudit extension or the audit logs of managed services, SQL Server Audit, or MySQL Enterprise Audit.
Common Mistakes
Collecting "just in case". Every extra column is something to protect, and something to leak.
Storing passwords reversibly. Encrypted passwords can be decrypted by whoever gets the key.
Real customer data in test databases. Use generated or anonymized data for development and testing.
Logging sensitive values. Query logs and error messages can contain the data you protected in the table.
Interview Corner
How should passwords be stored?
As a hash from a slow, salted password-hashing algorithm such as Argon2id, bcrypt or scrypt, computed in the application. Never as plain text, never encrypted, and never with fast hashes like MD5 or SHA-256.
What's the difference between encryption in transit and at rest?
In transit protects data moving over the network (TLS between app and database). At rest protects stored data, such as disks and backups, from being read if they're stolen.
What is data masking?
Showing a partly hidden version of sensitive values, such as s***@example.com, to users who don't need the real ones, often through views combined with privileges.
Practice
Challenge: Create a view payments_for_reports that shows each payment's id, the student's first name, the amount and the month paid (as the first day of the month), without due dates or methods. Grant it to a reporting role and show the view as that role.
Show solution
CREATE VIEW payments_for_reports AS
SELECT p.payment_id,
s.first_name,
p.amount_usd,
date_trunc('month', p.paid_on)::DATE AS paid_month
FROM payments AS p
JOIN students AS s ON s.student_id = p.student_id;
CREATE ROLE reporting NOLOGIN;
GRANT SELECT ON payments_for_reports TO reporting;
SET ROLE reporting;
SELECT * FROM payments_for_reports ORDER BY payment_id;
RESET ROLE;CREATE VIEW
CREATE ROLE
GRANT
SET
payment_id | first_name | amount_usd | paid_month
------------+------------+------------+------------
1 | Srihitha | 450.00 | 2025-08-01
2 | Srihitha | 250.00 | 2025-10-01
3 | Srihitha | 250.00 | 2025-12-01
4 | Srihitha | 550.00 | 2025-12-01
5 | Srihitha | 200.00 | 2026-01-01
6 | Navika | 225.00 | 2025-11-01
7 | Navika | 225.00 | 2025-12-01
(7 rows)
RESETThe reporting role sees only what reports need: no exact dates, due dates or methods, and no access to the tables underneath.
Key Takeaways
| You want to | Use |
|---|---|
| Store a password | An Argon2id or bcrypt hash string from the app |
| Hide part of a value | A view with regexp_replace or overlay |
| Limit who sees what | GRANT SELECT ON view, no grant on the table |
| Log changes | An AFTER UPDATE trigger writing current_user |
Was this tutorial helpful?