Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Write a PostgreSQL trigger that sets updated_at = now() on every UPDATE of the customer table, and explain BEFORE vs AFTER and row-level vs statement-level triggers.

We write a trigger function that sets NEW.updated_at := now() and returns NEW, and attach it with CREATE TRIGGER ... BEFORE UPDATE ON customer FOR EACH ROW EXECUTE FUNCTION set_updated_at(). BEFORE row triggers run before the row is written, so they can change NEW or skip the row by returning NULL; AFTER triggers see the final row and suit side effects such as audit rows. Row-level triggers fire once per changed row, statement-level triggers once per statement, and with transition tables a statement trigger can process all changed rows at once; all of them run inside the same transaction as the change.

Why this question is asked

An updated_at column maintained by the database is one of the most common uses of a trigger, and a good one: every write path, including a manual fix in psql or a script from another team, keeps the timestamp correct. Interviewers ask it because the small example opens up the important questions: when a trigger runs, what it can change, what it costs, and how the Java side sees the value. In this answer, we will write the trigger, test it, compare BEFORE and AFTER and row and statement triggers with examples, look at the cost, and finish with how Hibernate learns about the new value.

1A Quick Recap of Triggers

A trigger tells PostgreSQL to call a function automatically when something happens to a table, such as an INSERT, UPDATE or DELETE. In PostgreSQL the logic lives in a special function that returns the type trigger, and the trigger itself connects that function to a table and an event. Inside a row-level trigger function, two variables describe the row: OLD is the row as it was before the change, and NEW is the row as it will be written. For an UPDATE both exist; for an INSERT only NEW, and for a DELETE only OLD.

2Writing the updated_at Trigger

The function sets the column on the new row and returns it. The trigger runs it before every update of each row.

SQL
CREATE TABLE customer (id bigint PRIMARY KEY, name text NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now());
CREATE OR REPLACE FUNCTION set_updated_at() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
NEW.updated_at := now();
RETURN NEW; -- the row PostgreSQL will actually write
END
$$;
CREATE TRIGGER customer_updated
BEFORE UPDATE ON customer
FOR EACH ROW EXECUTE FUNCTION set_updated_at();
INSERT INTO customer (id, name) VALUES (1, 'Priya'); -- updated_at = 09:00:00 (the default)
UPDATE customer SET name = 'Priya R' WHERE id = 1; -- at 09:05
SELECT updated_at FROM customer WHERE id = 1; -- 09:05:00
UPDATE customer SET updated_at = '2000-01-01' WHERE id = 1;
SELECT updated_at FROM customer WHERE id = 1; -- 09:06:00, the trigger overrides it

Notice the last two statements: even an explicit attempt to set an old timestamp is overridden, because the trigger runs after the SET clause has built NEW. That is usually what we want for an audit-like column. Also notice that now() returns the start time of the transaction, so every row updated in one transaction gets the same timestamp; clock_timestamp() would give the real time of each row. And the trigger fires even when an UPDATE changes nothing; adding WHEN (OLD IS DISTINCT FROM NEW) to CREATE TRIGGER skips those rows. EXECUTE FUNCTION is the syntax since PostgreSQL 11; older scripts say EXECUTE PROCEDURE.

3BEFORE Versus AFTER

A BEFORE row trigger runs before the row is written, so it can still change it. Whatever it returns is what gets stored: it can return NEW unchanged, return a modified NEW, as ours does, or return NULL to skip this row silently, which can be used to ignore certain changes. BEFORE triggers are for adjusting or validating the row itself.

An AFTER row trigger runs after the row has been written and all BEFORE triggers have had their say, so it sees the final version, and its return value is ignored. AFTER triggers are for side effects that depend on the final row, such as writing an audit record to another table or notifying a queue.

SQL
CREATE TABLE customer_audit (customer_id bigint, old_name text, new_name text,
changed_at timestamptz, changed_by text);
CREATE FUNCTION audit_customer() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO customer_audit VALUES (NEW.id, OLD.name, NEW.name, NEW.updated_at, current_user);
RETURN NULL; -- ignored for AFTER triggers
END $$;
CREATE TRIGGER customer_audit_row
AFTER UPDATE ON customer
FOR EACH ROW EXECUTE FUNCTION audit_customer();
UPDATE customer SET name = 'P. Rao' WHERE id = 1;
SELECT old_name, new_name FROM customer_audit; -- Priya R | P. Rao

4Row-Level Versus Statement-Level

FOR EACH ROW fires once per affected row. An UPDATE that changes 100,000 rows calls the function 100,000 times. FOR EACH STATEMENT fires once per statement, even if it changes zero rows, and has no OLD or NEW. On its own, a statement trigger cannot see which rows changed, but since PostgreSQL 10, an AFTER trigger can declare transition tables: REFERENCING OLD TABLE AS ... NEW TABLE AS ... gives it every changed row as a table it can query. That lets us replace 100,000 single-row inserts with one set-based INSERT ... SELECT.

SQL
CREATE FUNCTION audit_customer_bulk() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO customer_audit
SELECT n.id, o.name, n.name, n.updated_at, current_user
FROM new_rows n JOIN old_rows o ON o.id = n.id;
RETURN NULL;
END $$;
CREATE TRIGGER customer_audit_stmt
AFTER UPDATE ON customer
REFERENCING OLD TABLE AS old_rows NEW TABLE AS new_rows
FOR EACH STATEMENT EXECUTE FUNCTION audit_customer_bulk();
UPDATE customer SET name = upper(name); -- 100000 rows changed, the function runs once
Choosing a trigger type
TypeFiresCan change the row?Typical use
BEFORE ... FOR EACH ROWonce per row, before writeyes, or skip with NULLupdated_at, normalising values
AFTER ... FOR EACH ROWonce per row, after writenoper-row audit, small tables
AFTER ... FOR EACH STATEMENT + transition tablesonce per statementnobulk audit, set-based work
BEFORE ... FOR EACH STATEMENTonce per statementnopermission or state checks
Use BEFORE ROW to shape the row, AFTER triggers for effects; prefer statement level for bulk work.

Transition tables work only with AFTER triggers, and BEFORE statement triggers cannot change rows, so the updated_at trigger must stay a BEFORE row trigger.

5Triggers Share the Transaction and Its Cost

Every trigger runs inside the transaction of the statement that fired it. If the audit insert fails, for example because the audit table is full or a constraint is violated, the original UPDATE fails and rolls back with it. That gives triggers their strength, the change and its side effect are atomic, but also their cost. Each row trigger adds a function call and possibly another write to every affected row, and that cost is paid by every writer of the table, often without the writer knowing the trigger exists. A trigger that makes each update 30 percent slower is invisible in code review of the application, so we keep trigger logic small, documented and in the same migrations as the tables.

6Follow-up questions

How would Hibernate know about updated_at if the trigger sets it?

By default it does not: after an update, the entity in memory still holds the old value. We tell Hibernate the column is generated by the database. In Hibernate 6.2 and later, @Generated(event = {EventType.INSERT, EventType.UPDATE}) on the field makes Hibernate read the value back after each write, on PostgreSQL usually through RETURNING or a follow-up select, and we mark the column insertable = false, updatable = false so Hibernate never writes it. Alternatively we call entityManager.refresh(entity), or use Hibernate's @UpdateTimestamp and set the value in the application, keeping the trigger only as a safety net for other writers; check your Hibernate version for the exact annotation attributes.

Does the trigger fire for rows changed through Hibernate bulk updates?

Yes. Triggers fire for every UPDATE that reaches the table, whether from Hibernate, a JPQL bulk update, native SQL or psql. That is exactly the advantage over setting the timestamp in Java, which only covers changes made through the entity.

Can I disable a trigger temporarily?

ALTER TABLE customer DISABLE TRIGGER customer_updated turns it off for everyone until it is enabled again, and it takes a lock on the table. It is meant for planned maintenance such as a bulk load, with a clear plan to re-enable it and to handle what the trigger would have done.

7Conclusion

In this answer, we wrote a BEFORE UPDATE row trigger that sets NEW.updated_at := now() and returns NEW, so every write path keeps the column correct. BEFORE row triggers can modify NEW or skip the row by returning NULL, while AFTER triggers see the final row and suit side effects such as audit records. Row-level triggers fire per row, statement-level triggers once per statement, and transition tables let a statement trigger process all changed rows at once. Triggers run in the same transaction, so their failures roll back the change and their cost is added to every write.

What to say in the interviewAbout 90 seconds aloud

Open with

I would write a trigger function, set_updated_at, returning trigger in PL/pgSQL, whose body sets NEW.updated_at to now() and returns NEW. Then CREATE TRIGGER customer_updated BEFORE UPDATE ON customer FOR EACH ROW EXECUTE FUNCTION set_updated_at.

Then, if they want more

It has to be BEFORE and row level, because only a BEFORE row trigger can change the row that is about to be written; whatever it returns is what gets stored, and returning NULL would skip the row. now() is the transaction start time, so all rows in one transaction get the same value, and I might add WHEN OLD IS DISTINCT FROM NEW to skip no-op updates.

AFTER triggers run once the row is written, see the final values, and their return value is ignored, so they are for side effects like writing an audit row.

Row-level triggers fire once per changed row; statement-level triggers fire once per statement, even for zero rows, and with transition tables, REFERENCING NEW TABLE AS new_rows, an AFTER statement trigger can process all changed rows in one set-based query, which is much cheaper for bulk changes.

Triggers run inside the same transaction, so if one fails the whole statement rolls back, and their cost is added to every write. On the Java side, I would map updated_at with Hibernate's @Generated for insert and update, so Hibernate reads the database value back.

About this answer

Last updated
12 November 2026
Versions it names
Hibernate 6, PostgreSQL 10, PostgreSQL 11
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write a PostgreSQL trigger that sets updated_at = now() on every UPDATE of the customer...": https://scrivio-interview-library.netlify.app/databases/stored-code/6c78b50bfe/