A Postgres audit log in one trigger: row history and "as of" queries in plain SQL
Build an audit log for any Postgres table with one generic PL/pgSQL trigger and a JSONB history table: who changed what and when, only the columns that changed, and a function that returns the table as it was at any past moment. Includes the traps (TRUNCATE, SET ROLE, connection poolers) and measured overhead on PostgreSQL 17.11.
On this page
"Who changed this order, and what did it look like last Tuesday?" You can answer that inside Postgres, without a change-data-capture pipeline or an extra service. One generic trigger function writes every insert, update and delete on the tables you choose into a single JSONB history table, together with who made the change, the values it replaced, and the transaction it belonged to. A dozen-line SQL function then turns that history back into typed rows: the whole table as it was at any moment you ask for. This post builds both in under 100 lines of SQL, and covers the parts that are easy to get wrong: updates that change nothing, TRUNCATE, recording the right user behind SET ROLE and connection poolers, and what the trigger costs. We measured that last part: on our machine, a write-only benchmark of single-row updates went from about 23,300 to 17,800 transactions per second, and bulk inserts and updates of 100,000 rows took about 11 times as long. Every statement and every output below comes from a local PostgreSQL 17.11, the major version Relyt One runs.
| What you want | How this design does it |
|---|---|
| One audit setup for many tables | One SECURITY DEFINER trigger function, attached per table with audit.enable('orders') |
| See only what changed | old_values holds the previous value of each changed column; updates that change nothing aren't logged |
| Know who did it | actor from a transaction-local setting the application sets; db_user from session_user |
| Read the table as it was | audit.as_of(NULL::orders, '<timestamp>') rebuilds typed rows from the log |
| Keep the log honest | Application roles can't read or write audit.log; TRUNCATE on audited tables is refused |
| Know the price | About 24% fewer single-row updates per second in a write-only test; bulk inserts and updates about 11x slower, bulk deletes far more |
Every audited table writes to the same table. Each row is one change to one row:
CREATE SCHEMA audit;
CREATE TABLE audit.log (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
tbl regclass NOT NULL,
row_id text NOT NULL,
op text NOT NULL CHECK (op IN ('INSERT', 'UPDATE', 'DELETE')),
changed_at timestamptz NOT NULL DEFAULT now(),
xact_id xid8 NOT NULL DEFAULT pg_current_xact_id(),
actor text DEFAULT nullif(current_setting('app.actor', true), ''),
db_user text NOT NULL DEFAULT session_user,
row_data jsonb NOT NULL, -- the row after the change (before, for DELETE)
old_values jsonb -- UPDATE only: previous values of the changed columns
);
CREATE INDEX log_row_idx ON audit.log (tbl, row_id, id);
CREATE INDEX log_time_idx ON audit.log (tbl, changed_at);A few choices here matter later:
tblis aregclass, stored as the table's OID. It prints as the table name, and it survivesALTER TABLE ... RENAME. The flip side: if you drop the table, those log rows point at an OID that no longer exists.row_datais the full row, not just a diff. That costs space, but it means any single log row tells you the complete state of the record after that change, which is what makes the "as of" query below a single pass over the log instead of a replay of diffs.old_valuesholds only the columns that changed, with their previous values. Together withrow_datait gives you a before/after view without storing the whole old row.changed_atisnow(), which in Postgres is the start time of the current transaction, not the moment the statement ran. Every change made by one transaction gets the same timestamp, andxact_idtells you which changes belong together.
The trigger doesn't know anything about the table it's attached to. It converts OLD and NEW to JSONB, works out which keys differ, and writes one log row. The only thing it needs from you is the name of the primary key column, passed as a trigger argument:
CREATE FUNCTION audit.capture() RETURNS trigger
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
DECLARE
pk text := TG_ARGV[0];
new_j jsonb := CASE WHEN TG_OP <> 'DELETE' THEN to_jsonb(NEW) END;
old_j jsonb := CASE WHEN TG_OP <> 'INSERT' THEN to_jsonb(OLD) END;
before jsonb;
BEGIN
IF TG_OP = 'UPDATE' THEN
SELECT jsonb_object_agg(o.key, o.value) INTO before
FROM jsonb_each(old_j) AS o
WHERE o.value IS DISTINCT FROM new_j -> o.key;
IF before IS NULL THEN
RETURN NULL; -- nothing changed: don't log
END IF;
END IF;
INSERT INTO audit.log (tbl, row_id, op, row_data, old_values)
VALUES (TG_RELID, coalesce(new_j, old_j) ->> pk, TG_OP, coalesce(new_j, old_j), before);
RETURN NULL;
END;
$$;Three details make this safe to attach to tables your application writes to:
SECURITY DEFINERruns the function with the privileges of its owner, so the application role doesn't need any rights onaudit.log. That's the point: a role that can write to the log can also forge or delete entries.SET search_path = pg_catalog, pg_tempis the hardening the PostgreSQL documentation recommends for everySECURITY DEFINERfunction, so a caller can't put their own objects in front of the ones the function uses. Everything in the body is either a built-in or schema-qualified.RETURN NULLis fine because this will be anAFTERrow trigger, whose return value Postgres ignores. The early return for updates wherebeforeis empty is what skips no-op updates: an ORM that writesUPDATE orders SET status = 'paid'on an already-paid order leaves no noise in the log.
Row-level triggers don't fire for TRUNCATE. Without a guard, TRUNCATE orders empties the table and the log never hears about it. The simplest honest answer is to refuse it on audited tables and make people use DELETE, which is logged row by row. A small helper checks the table, attaches both triggers, and logs the rows that are already there, so the history has a starting point (more on why in the "as of" section):
CREATE FUNCTION audit.no_truncate() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE EXCEPTION 'TRUNCATE on % is not audited; use DELETE', TG_TABLE_NAME;
END;
$$;
CREATE FUNCTION audit.enable(t regclass, pk text DEFAULT 'id') RETURNS void
LANGUAGE plpgsql AS $$
BEGIN
IF (SELECT relkind FROM pg_class WHERE oid = t) <> 'r' THEN
RAISE EXCEPTION '% is not a plain table', t;
END IF;
IF NOT EXISTS (SELECT FROM pg_attribute
WHERE attrelid = t AND attname = pk AND attnum > 0 AND NOT attisdropped) THEN
RAISE EXCEPTION 'column % does not exist in %', pk, t;
END IF;
EXECUTE format('CREATE TRIGGER audit_row AFTER INSERT OR UPDATE OR DELETE ON %s
FOR EACH ROW EXECUTE FUNCTION audit.capture(%L)', t, pk);
EXECUTE format('CREATE TRIGGER audit_truncate BEFORE TRUNCATE ON %s
FOR EACH STATEMENT EXECUTE FUNCTION audit.no_truncate()', t);
-- baseline: log the rows that already exist, so as_of() can see them
EXECUTE format('INSERT INTO audit.log (tbl, row_id, op, row_data)
SELECT %L::regclass, to_jsonb(r) ->> %L, ''INSERT'', to_jsonb(r) FROM %s AS r',
t, pk, t);
END;
$$;
REVOKE ALL ON SCHEMA audit FROM PUBLIC;
REVOKE ALL ON audit.log FROM PUBLIC;
REVOKE EXECUTE ON FUNCTION audit.capture() FROM PUBLIC;Now an example table, and an application role that can do everything to it, including TRUNCATE:
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer text NOT NULL,
status text NOT NULL DEFAULT 'pending',
total numeric(10,2) NOT NULL
);
SELECT audit.enable('orders');
CREATE ROLE app LOGIN PASSWORD 'throwaway';
GRANT SELECT, INSERT, UPDATE, DELETE, TRUNCATE ON orders TO app;app gets no privileges on the audit schema at all, and EXECUTE on audit.capture() was revoked from PUBLIC above, as the PostgreSQL documentation recommends for SECURITY DEFINER functions. Neither stops the trigger: it fires whoever writes to the table, because the right to use the function is checked when the trigger is created. We checked that inserts by app are still logged. COPY ... FROM fires row triggers too, so bulk loads are logged like any other insert. We checked both as app, along with the things app must not be able to do:
postgres=> TRUNCATE orders;
ERROR: TRUNCATE on orders is not audited; use DELETE
postgres=> INSERT INTO audit.log (tbl, row_id, op, row_data) VALUES ('orders', '1', 'DELETE', '{}');
ERROR: permission denied for schema audit
postgres=> ALTER TABLE orders DISABLE TRIGGER audit_row;
ERROR: must be owner of table ordersThe database only knows which role connected. Your application usually knows more: the signed-in user, the support agent, the background job. Pass that in with a setting that lives only as long as the transaction, and the log's actor default picks it up:
BEGIN;
SELECT set_config('app.actor', 'support:li', true);
UPDATE orders SET status = 'paid' WHERE id = 1;
COMMIT;set_config(name, value, true) is the function form of SET LOCAL: it takes parameters, which makes it easy to call from application code, and it is reset at the end of the transaction. That last property is what makes it safe behind a transaction-pooling connection pooler, where the next transaction on the same server connection may belong to a different client. A session-level SET app.actor = ... would leak to that client and stamp its changes with the wrong name. (Our post on what breaks behind PgBouncer transaction pooling covers this pattern in detail.)
One quirk explains the nullif in the table definition. Once a custom setting like app.actor has been set in a session, reading it after the transaction ends returns an empty string, not NULL:
postgres=> SELECT current_setting('app.actor', true) IS NULL; -- before any set_config
t
postgres=> BEGIN; SELECT set_config('app.actor', 'x', true); COMMIT;
postgres=> SELECT current_setting('app.actor', true) IS NULL, current_setting('app.actor', true) = '';
f | tWithout nullif, rows written without an actor would sometimes say NULL and sometimes '', depending on what the connection did earlier.
db_user comes from session_user, and that's deliberate. Inside a SECURITY DEFINER function, current_user is the function's owner, so it would record the same name for every change. session_user is the role that logged in. The catch is SET ROLE: it changes current_user but not session_user. We ran the insert as postgres after SET ROLE app, and the log recorded postgres. If your stack connects as one role and switches with SET ROLE per request, as some API layers do, rely on actor for the real identity.
After an insert of two orders, the transaction above, an update that changed nothing, and a refund job that updated one order and deleted the other, the log holds five rows, not six:
id | row_id | op | actor | db_user | old_values | row_data
----+--------+--------+-------------+---------+-------------------------------------+---------------------------------------------------------------------
1 | 1 | INSERT | | app | | {"id": 1, "total": 120.00, "status": "pending", "customer": "ada"}
2 | 2 | INSERT | | app | | {"id": 2, "total": 75.50, "status": "pending", "customer": "grace"}
3 | 1 | UPDATE | support:li | app | {"status": "pending"} | {"id": 1, "total": 120.00, "status": "paid", "customer": "ada"}
4 | 1 | UPDATE | job:refunds | app | {"total": 120.00, "status": "paid"} | {"id": 1, "total": 0.00, "status": "refunded", "customer": "ada"}
5 | 2 | DELETE | job:refunds | app | | {"id": 2, "total": 75.50, "status": "pending", "customer": "grace"}The history of one row is a query on the (tbl, row_id, id) index:
SELECT changed_at, op, actor, old_values, row_data - 'id' AS row_after
FROM audit.log
WHERE tbl = 'orders'::regclass AND row_id = '1'
ORDER BY id;The more interesting question is "what did the whole table look like at 13:06:55?" Because each log row stores the complete row, the answer is: for every row_id, take the latest entry at or before that time, drop the rows whose latest entry is a delete, and turn the JSONB back into a typed row with jsonb_populate_record:
CREATE FUNCTION audit.as_of(_row anyelement, _ts timestamptz)
RETURNS SETOF anyelement LANGUAGE sql STABLE AS $$
SELECT jsonb_populate_record(_row, l.row_data)
FROM (
SELECT DISTINCT ON (row_id) op, row_data
FROM audit.log
WHERE tbl = pg_typeof(_row)::text::regclass
AND changed_at <= _ts
ORDER BY row_id, id DESC
) AS l
WHERE l.op <> 'DELETE';
$$;You pass a typed NULL to say which table you mean, and you get rows of that table's type back, so you can join and filter them like the real thing:
postgres=# SELECT * FROM audit.as_of(NULL::orders, '2026-11-09 13:06:55.003792+00');
id | customer | status | total
----+----------+---------+--------
1 | ada | paid | 120.00
2 | grace | pending | 75.50
postgres=# SELECT * FROM audit.as_of(NULL::orders, now());
id | customer | status | total
----+----------+----------+-------
1 | ada | refunded | 0.00The function runs with the caller's privileges, so only roles you allow to read audit.log can use it. Rows come back in row_id order compared as text (1, 10, 2), so add your own ORDER BY. If you add a column to orders later, older log rows return NULL for it, because jsonb_populate_record fills missing keys with NULL. And the function only knows what's in the log: that's why audit.enable logs every existing row when you turn auditing on. Without that baseline, a row that existed before and was never changed afterwards would be missing from every answer, even as_of(now()). The earliest moment you can ask about is when you ran audit.enable.
Every audited write now does a second insert, into a table with two indexes and a JSONB column. We measured that in a throwaway postgres:17.11-alpine container with default settings (shared_buffers 128 MB, synchronous_commit on) on an Apple M1 Pro with 5 CPUs allotted to Docker. The table had five columns and a bigint primary key, like a small orders table.
Single-row updates by primary key, pgbench with 8 clients for 20 seconds, each mode run twice:
| Setup | Transactions per second | Average latency |
|---|---|---|
| No trigger | 22,834 / 23,760 | 0.350 / 0.337 ms |
| Audit trigger | 17,763 / 17,767 | 0.450 / 0.450 ms |
That's about 24% fewer transactions per second when the database does nothing but these updates, with 8 clients keeping 5 CPUs busy (pgbench ran in the same container). In a real application, where each request also reads, waits on the network and runs your code, the share is smaller.
Bulk statements on 100,000 rows (median of three runs, milliseconds):
| Setup | INSERT | UPDATE every row | UPDATE that changes nothing | DELETE every row |
|---|---|---|---|---|
| No trigger | 135 | 215 | 291 | 25 |
| Row-level trigger | 1,553 | 2,417 | 1,146 | 1,572 |
| Statement-level trigger (below) | 721 | 2,043 | 1,278 | 707 |
Bulk writes pay for the trigger on every row: 14 to 22 microseconds each in this test, which turns a 135 ms insert into a 1.5 second one and a 25 ms delete into a 1.6 second one. Plan big backfills and data fixes with that in mind. The no-op update is cheaper than a real one because the trigger compares and exits without writing, but it still converts both rows to JSONB.
Storage: the 200,000 log rows from one insert and one update of 100,000 rows took 59,179,008 bytes, about 296 bytes per change including both indexes, for a five-column row. Wider rows cost more, because row_data stores the whole row every time. Plan for growth: if you keep history for years, partitioning audit.log by month on changed_at lets you drop old months instead of deleting rows one by one. The primary key of a partitioned table has to include the partition key, so it becomes (id, changed_at).
Postgres can also call a trigger once per statement and hand it every affected row at once in "transition tables" (REFERENCING OLD TABLE AS ... NEW TABLE AS ...). One call per statement instead of one per row sounds faster, and for bulk writes it partly is. In our runs it halved the cost of a 100,000-row INSERT or DELETE, made UPDATE about 15% faster, and made the update that changes nothing slightly slower. An update has to match each old row to its new version by primary key and diff the two, and that join and diff ate most of the savings. Two limitations decided it for us: a trigger with transition tables can only be defined for a single event (Postgres rejects AFTER INSERT OR DELETE ... REFERENCING with "transition tables cannot be specified for triggers with more than one event"), so you need three triggers per table, and the old/new matching breaks if a statement changes the primary key. We didn't benchmark it on single-row writes, where each statement touches one row anyway. For tables written mostly by single-row requests, we'd keep the row-level trigger: one function, one trigger, and no old/new matching to get wrong.
- It records what went through the trigger. The table owner can disable it with
ALTER TABLE ... DISABLE TRIGGER, and a superuser can skip triggers entirely. This is an application audit trail, not tamper-proof evidence. If you need the latter, ship the log somewhere the database's owner can't rewrite. - Plain tables only. On a partitioned table, Postgres copies the row trigger to each partition, which then logs the partition's name instead of the parent's, and the
TRUNCATEguard isn't copied at all.audit.enablerefuses anything that isn't a plain table; audit partitions one by one or extend the functions if you need it. - Time is transaction start time.
as_ofplaces a transaction at the moment it began. A long transaction that began before your timestamp but committed after it shows up in the answer, even though nobody could see its changes at that moment. Usexact_idto group the changes, and keep audited transactions short. - Primary keys should not change, and should be simple.
row_idis the key's JSON text, which is stable for integer, text and uuid keys. For atimestamptzkey, that text depends on the session's time zone, so the same row can end up under tworow_ids. Composite keys need a different expression. If an update changes the key, the log files the new version under the newrow_idand the oldrow_idnever gets a delete entry, soas_ofreturns the row twice. We tried it on a table keyed by a textcode: after renamingbasictostarter,as_of(NULL::plans, now())returned both. An identity column declaredGENERATED ALWAYS, likeorders.id, refuses such updates ("column "id" can only be updated to DEFAULT"). - Schema changes.
jsonb_populate_recordignores keys for columns you've dropped and returnsNULLfor columns added later. But it converts stored values to the current column types, so a type change can break reads of old rows: after changingorders.totaltointeger,as_offailed withinvalid input syntax for type integer: "0.00". Cast in the query, or keep a copy of the old definition, when you change types on an audited table.
An audit log answers questions about individual rows over months: who refunded this order, what did this customer's plan look like before support changed it. It is also how you build "undo" and change feeds into the product itself.
The other kind of question is "the migration at 10:40 broke something, what did the database look like at 10:30?" For that you want every table at once, including the ones you never audited. On Relyt One, a branch can start from its parent's data at a past moment inside the project's history retention window (up to 3 hours, set under History retention in project settings): create a branch, pick Past data and a time, and you get the database as it was then, on its own compute, sharing unchanged pages with the parent instead of copying them. You can query it, compare it with the current data, and copy back what you need. It is also a good place to try the trigger above: enable it on a branch, replay your heaviest job and see what the overhead is with your own data before you turn it on in production.
The two fit together. The audit log covers the long tail of row-level history for the tables you care about. Branching from the past covers everything for the last few hours, with no setup.



