← Back to SQL, page 18

sql-0347 · Medium mid

Design an audit log that records who changed what in important tables.

Write an append-only audit table with the table name, row key, action, old and new values (for example as JSON), the acting user and a timestamp. Fill it from triggers so no code path can skip it, pass the user through a session setting, and restrict UPDATE and DELETE on the audit table itself.

Full answer
text
audit_log(id bigint PK, table_name, row_pk, action CHECK IN ('I','U','D'),
          old_data jsonb, new_data jsonb, changed_by, changed_at timestamptz DEFAULT now())

Design points:

  • Triggers on each audited table capture changes from every client, including scripts and admin tools.
  • The application sets the acting user per transaction (SET LOCAL app.user_id = '42') and the trigger reads it with current_setting.
  • Store only changed columns on update if volume matters.
  • Make the log append-only: grant INSERT but not UPDATE or DELETE to the application role.
  • Index (table_name, row_pk, changed_at) for "history of this record".
  • Partition by month and archive old partitions if the log grows quickly.

Application-level logging is simpler to start but misses changes made outside the app. Change data capture from the write-ahead log is another option for streaming changes to other systems.

Key points

  • Append-only table with old and new values
  • Triggers make the log complete
  • Pass the acting user via a session setting
  • Restrict modification of the log
  • Index for per-record history

Common mistakes

  • Logging only in application code
  • Letting the application role edit audit rows

Follow-ups

  • How would you show a record's history in the UI?
  • How does change data capture differ from triggers?

Tips

  • Explain why triggers are used