Auditing — Complete Guide
Auditing — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of PostgreSQL Tutorial on Toolliyo Academy.
On this page
PostgreSQL Tutorial · Lesson 48 of 100
Auditing
SQL ✓ → Advanced
Advanced · 2 — Production · ~6 min · PostgreSQL — Functions & Automation
What is this?
Auditing tracks who changed what and when — triggers writing audit tables, pgaudit extension logging statements, or logical decoding for change streams.
Why should you care?
Healthcare PostgresVerse must prove who viewed patient record — audit columns plus session user logging.
See it live — copy this example
Run in pgAdmin or psql.
CREATE TABLE patients_audit (
audit_id bigserial PRIMARY KEY,
patient_id bigint,
action text,
changed_by text DEFAULT current_user,
changed_at timestamptz DEFAULT now(),
row_data jsonb
);
CREATE OR REPLACE FUNCTION audit_patient_changes()
RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO patients_audit (patient_id, action, row_data)
VALUES (COALESCE(NEW.patient_id, OLD.patient_id), TG_OP, to_jsonb(COALESCE(NEW, OLD)));
RETURN COALESCE(NEW, OLD);
END;
$$;
What happened?
- Trigger captures INSERT/UPDATE/DELETE into patients_audit with full row json and current_user.
- Append-only audit supports forensic review.
Practice next
- Create patients table and audit table.
- Attach trigger FOR EACH ROW on patients.
- INSERT/UPDATE/DELETE sample patient; query audit.
- Add action filter query for DELETE only last 7 days.
- Compare trigger audit vs logical replication change feed.
Remember
Triggers give row-level audit trail. current_user and inet_client_addr identify session. pgaudit adds statement-level enterprise logging.
PostgresVerse HIPAA review
Auditor requests proof of access to patient 9912; patients_audit answers with timestamps.
Outcome: Hospital passes compliance; redaction policy added for sensitive fields.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!