Database Design Patterns · Lesson 74 of 112

Database Audit Logs and History Tables

What you will learn

  • What an audit log is and why you may need one
  • How to write it in the same transaction as the change
  • How a trigger can do it automatically (a first look; triggers are lesson 11.1)
  • How to make the log append-only

When a price changes, a stock count drops or a customer disappears, someone will eventually ask: who did that, and what was it before? A normal table only holds the current state. An audit log keeps the story.

1. A simple audit table

This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). It watches one column of a real table and adds a log table and triggers of its own to your browser's copy; run the examples from top to bottom, and Reset data starts again.

We audit changes to the price of a product.

We audit changes to the status of an account.

We audit changes to the credits of a course.

CREATE TABLE change_log (
  id INTEGER PRIMARY KEY, at TEXT NOT NULL DEFAULT (datetime('now')),
  who TEXT NOT NULL, table_name TEXT NOT NULL, row_id INTEGER NOT NULL,
  action TEXT NOT NULL CHECK (action IN ('INSERT','UPDATE','DELETE')),
  old_value TEXT, new_value TEXT);
(done)
CREATE TABLE change_log (
  id INTEGER PRIMARY KEY, at TEXT NOT NULL DEFAULT (datetime('now')),
  who TEXT NOT NULL, table_name TEXT NOT NULL, row_id INTEGER NOT NULL,
  action TEXT NOT NULL CHECK (action IN ('INSERT','UPDATE','DELETE')),
  old_value TEXT, new_value TEXT);
(done)
CREATE TABLE change_log (
  id INTEGER PRIMARY KEY, at TEXT NOT NULL DEFAULT (datetime('now')),
  who TEXT NOT NULL, table_name TEXT NOT NULL, row_id INTEGER NOT NULL,
  action TEXT NOT NULL CHECK (action IN ('INSERT','UPDATE','DELETE')),
  old_value TEXT, new_value TEXT);
(done)

Each audit row says who, when (UTC, lesson 10.2), which table and row, what action, and the old and new values.

Quick check: Why should an audit log be written in the same transaction as the change?

So the two succeed or fail together: you never have a change with no log entry, or a log entry for a change that was rolled back.

2. Writing the log from the application

The key rule: the change and its log entry must be in one transaction (lesson 6.2), so one cannot exist without the other. Here two people change the same row, each in one transaction:

BEGIN;
INSERT INTO change_log (who, table_name, row_id, action, old_value, new_value)
VALUES ('amy', 'products', 1, 'UPDATE', (SELECT price FROM products WHERE product_id = 1), 12.0);
UPDATE products SET price = 12.0 WHERE product_id = 1;
COMMIT;
(1 row changed)
BEGIN;
INSERT INTO change_log (who, table_name, row_id, action, old_value, new_value)
VALUES ('joe', 'products', 1, 'UPDATE', (SELECT price FROM products WHERE product_id = 1), 11.0);
UPDATE products SET price = 11.0 WHERE product_id = 1;
COMMIT;
SELECT who, action, old_value, new_value FROM change_log ORDER BY id;
who  action  old_value  new_value
---  ------  ---------  ---------
amy  UPDATE  6.6        12.0
joe  UPDATE  12.0       11.0
(2 rows)
BEGIN;
INSERT INTO change_log (who, table_name, row_id, action, old_value, new_value)
VALUES ('amy', 'accounts', 1, 'UPDATE', (SELECT status FROM accounts WHERE account_id = 1), 'frozen');
UPDATE accounts SET status = 'frozen' WHERE account_id = 1;
COMMIT;
(1 row changed)
BEGIN;
INSERT INTO change_log (who, table_name, row_id, action, old_value, new_value)
VALUES ('joe', 'accounts', 1, 'UPDATE', (SELECT status FROM accounts WHERE account_id = 1), 'open');
UPDATE accounts SET status = 'open' WHERE account_id = 1;
COMMIT;
SELECT who, action, old_value, new_value FROM change_log ORDER BY id;
who  action  old_value  new_value
---  ------  ---------  ---------
amy  UPDATE  open       frozen
joe  UPDATE  frozen     open
(2 rows)
BEGIN;
INSERT INTO change_log (who, table_name, row_id, action, old_value, new_value)
VALUES ('amy', 'courses', 1, 'UPDATE', (SELECT credits FROM courses WHERE course_id = 1), 5);
UPDATE courses SET credits = 5 WHERE course_id = 1;
COMMIT;
(1 row changed)
BEGIN;
INSERT INTO change_log (who, table_name, row_id, action, old_value, new_value)
VALUES ('joe', 'courses', 1, 'UPDATE', (SELECT credits FROM courses WHERE course_id = 1), 3);
UPDATE courses SET credits = 3 WHERE course_id = 1;
COMMIT;
SELECT who, action, old_value, new_value FROM change_log ORDER BY id;
who  action  old_value  new_value
---  ------  ---------  ---------
amy  UPDATE  4          5
joe  UPDATE  5          3
(2 rows)

This knows who (the application knows the logged-in user). Its weakness: any code path that forgets to call it, or anyone using the database directly, leaves no trace.

3. Writing the log with a trigger

A trigger is code stored in the database that runs automatically when a row changes (lesson 11.1 covers them properly). Triggers catch changes from any source:

CREATE TRIGGER products_audit AFTER UPDATE OF price ON products
BEGIN
  INSERT INTO change_log (who, table_name, row_id, action, old_value, new_value)
  VALUES ('(unknown)', 'products', NEW.product_id, 'UPDATE', OLD.price, NEW.price);
END;
UPDATE products SET price = 9.0 WHERE product_id = 1;
SELECT who, action, old_value, new_value FROM change_log ORDER BY id DESC LIMIT 1;
who        action  old_value  new_value
---------  ------  ---------  ---------
(unknown)  UPDATE  11.0       9.0
(1 row)
CREATE TRIGGER accounts_audit AFTER UPDATE OF status ON accounts
BEGIN
  INSERT INTO change_log (who, table_name, row_id, action, old_value, new_value)
  VALUES ('(unknown)', 'accounts', NEW.account_id, 'UPDATE', OLD.status, NEW.status);
END;
UPDATE accounts SET status = 'closed' WHERE account_id = 1;
SELECT who, action, old_value, new_value FROM change_log ORDER BY id DESC LIMIT 1;
who        action  old_value  new_value
---------  ------  ---------  ---------
(unknown)  UPDATE  open       closed
(1 row)
CREATE TRIGGER courses_audit AFTER UPDATE OF credits ON courses
BEGIN
  INSERT INTO change_log (who, table_name, row_id, action, old_value, new_value)
  VALUES ('(unknown)', 'courses', NEW.course_id, 'UPDATE', OLD.credits, NEW.credits);
END;
UPDATE courses SET credits = 2 WHERE course_id = 1;
SELECT who, action, old_value, new_value FROM change_log ORDER BY id DESC LIMIT 1;
who        action  old_value  new_value
---------  ------  ---------  ---------
(unknown)  UPDATE  3          2
(1 row)

The trigger recorded the change, but it does not know who: SQLite triggers cannot see the application's user. Some systems let the application set a session value the trigger can read; syntax differs, so check your own system. Note also that the application-written entries and the trigger would both fire if you used both for the same change, giving two rows. Pick one method per table.

4. Make the log append-only

An audit log that can be edited proves nothing. You can block changes with triggers (in systems with users and permissions, also remove the right to change the table, lesson 8.4):

CREATE TRIGGER audit_no_update BEFORE UPDATE ON change_log BEGIN SELECT RAISE(ABORT, 'audit rows cannot be changed'); END;
CREATE TRIGGER audit_no_delete BEFORE DELETE ON change_log BEGIN SELECT RAISE(ABORT, 'audit rows cannot be deleted'); END;
(done)
UPDATE change_log SET who = 'nobody';
IntegrityError: audit rows cannot be changed
DELETE FROM change_log;
IntegrityError: audit rows cannot be deleted
SELECT COUNT(*) AS log_rows FROM change_log;
log_rows
--------
       3
(1 row)
CREATE TRIGGER audit_no_update BEFORE UPDATE ON change_log BEGIN SELECT RAISE(ABORT, 'audit rows cannot be changed'); END;
CREATE TRIGGER audit_no_delete BEFORE DELETE ON change_log BEGIN SELECT RAISE(ABORT, 'audit rows cannot be deleted'); END;
(done)
UPDATE change_log SET who = 'nobody';
IntegrityError: audit rows cannot be changed
DELETE FROM change_log;
IntegrityError: audit rows cannot be deleted
SELECT COUNT(*) AS log_rows FROM change_log;
log_rows
--------
       3
(1 row)
CREATE TRIGGER audit_no_update BEFORE UPDATE ON change_log BEGIN SELECT RAISE(ABORT, 'audit rows cannot be changed'); END;
CREATE TRIGGER audit_no_delete BEFORE DELETE ON change_log BEGIN SELECT RAISE(ABORT, 'audit rows cannot be deleted'); END;
(done)
UPDATE change_log SET who = 'nobody';
IntegrityError: audit rows cannot be changed
DELETE FROM change_log;
IntegrityError: audit rows cannot be deleted
SELECT COUNT(*) AS log_rows FROM change_log;
log_rows
--------
       3
(1 row)

A person with full control of the database file can still remove such triggers, so for strong guarantees the log should also be copied elsewhere.

5. Choices to make

Question Options
What to store only changed columns, or the whole old row (a history table with the same columns plus a time)
Which tables usually those about money, permissions and personal data, not every table
Size logs grow quickly; plan retention and archiving (lesson 10.3)
Privacy the log holds old personal data too; apply the same protection (lesson 8.6)

Worked example: who changed the price?

A customer says the tea cost 10.00 last week but 12.00 now. The owner queries the log: SELECT at, who, old_value, new_value FROM audit_log WHERE table_name = 'products' AND row_id = 1. It shows that Amy changed it from 1000 to 1200, so the dispute is settled with facts. Without the log, nobody could tell. The data is made up.

Common mistakes

  • Writing the log in a separate transaction from the change.
  • Logging everything, filling storage with noise nobody reads.
  • A log table anyone can edit.
  • Logging secrets (passwords, card numbers) in plain text.

Key takeaways

  • An audit log records who changed what, when, and the old and new values.
  • Write it in the same transaction as the change.
  • Application code knows the user; triggers catch every change but may not know the user.
  • Make the log append-only and protect it.
  • Log what matters, and treat logged data as sensitive too.

Practice

1. What columns does a useful audit row need?

Show answer

When, who, which table and row, the action, and the old and new values.

2. Why must the log entry and the change be in one transaction?

Show answer

So both happen or neither does; otherwise a change could exist without a record, or a record without a change.

3. One advantage and one disadvantage of triggers for auditing?

Show answer

They catch changes from any source; but in SQLite they do not know which application user made the change.

4. How can you stop people from editing the audit table?

Show answer

Triggers that abort updates and deletes, and removing change permissions in systems that have users and permissions.

5. Why is the audit log a privacy concern?

Show answer

It keeps old values, which may include personal data, so it needs the same protection as the main tables.

6. Which tables in a shop would you audit first?

Show answer

Prices, payments and refunds, user permissions, and customer personal data.