Sub topic 10
Defaults, generated columns and triggers: what RETURNING reflects
This chapter assumes you can write INSERT, UPDATE and DELETE with a basic RETURNING list. It also assumes you know column defaults, identity columns and the idea of a row-level trigger. Here you will learn which version of a row RETURNING reports when defaults, generated columns and triggers all change it.
The rule: RETURNING shows the row as stored
RETURNING reports the row that PostgreSQL wrote to the table. It does not report the values you supplied in the statement. Several steps can change the row between your statement and the write:
- Column defaults and identity values fill in columns you left out.
BEFORErow triggers can rewrite the new row.- Stored generated columns are computed from the final values.
- Type coercion applies, for example rounding to
numeric(10,2).
RETURNING sees the result of all four. It does not see changes made by AFTER triggers, because those run after the row is written.
A table that exercises every layer
The following table has an identity key, defaults, a stored generated column and a BEFORE trigger.
CREATE TABLE invoices (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
net numeric(10,2) NOT NULL,
tax_rate numeric(4,3) NOT NULL DEFAULT 0.200,
gross numeric(12,2) GENERATED ALWAYS AS (round(net * (1 + tax_rate), 2)) STORED,
note text,
version integer NOT NULL DEFAULT 1,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE FUNCTION invoices_touch() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP = 'UPDATE' THEN
NEW.version := OLD.version + 1;
END IF;
NEW.note := nullif(trim(NEW.note), '');
NEW.updated_at := clock_timestamp();
RETURN NEW;
END;
$$;
CREATE TRIGGER invoices_touch
BEFORE INSERT OR UPDATE ON invoices
FOR EACH ROW EXECUTE FUNCTION invoices_touch();Defaults and identity values
Insert a row and name only the columns you care about:
INSERT INTO invoices (net, note)
VALUES (100, ' rush ')
RETURNING id, net, tax_rate, gross, note, version;The result is:
| id | net | tax_rate | gross | note | version |
|---|---|---|---|---|---|
| 1 | 100.00 | 0.200 | 120.00 | rush | 1 |
Each column shows a different layer:
idandtax_ratecame from the identity and the default.netis100.00, not100, because the column typenumeric(10,2)fixed the scale.noteisrushbecause theBEFOREtrigger trimmed the whitespace you sent.grossis120.00because PostgreSQL computed it from the finalnetandtax_rate.
Writing a value into a numeric(10,2) column rounds it silently, and RETURNING shows the rounded value. If you insert 1.239, you get 1.24 back. Use this to check what the database really kept.
`now()` versus `clock_timestamp()`
now() returns the start time of the current transaction. Every row inserted or updated in one transaction gets the same created_at and updated_at from a DEFAULT now(). In a script that updates the same row twice inside one transaction, RETURNING updated_at shows the same value both times. The trigger above uses clock_timestamp(), which returns the actual wall-clock time at each call, so those values differ.
Choose based on what you want to record. now() gives one consistent timestamp for the whole transaction. clock_timestamp() gives the moment each row was written.
Rolled-back and skipped identity values
The identity value is taken from a sequence before the row is written. If the statement later fails, for example on a unique violation, that number is consumed and never returned. Gaps in id are normal. Do not read anything into the numbers RETURNING hands you, other than that they are unique.
Generated columns
A stored generated column is computed after all BEFORE triggers have run. Two consequences follow:
RETURNINGshows the generated value that matches the final row, even when a trigger changed the inputs.- A
BEFOREtrigger cannot read the generated value for the row being written, so it cannot depend on it.
Update the invoice:
UPDATE invoices
SET net = 150
WHERE id = 1
RETURNING net, gross, version, updated_at > created_at AS touched;The result is net = 150.00, gross = 180.00, version = 2 and touched = true. You set only net. The trigger bumped version, and PostgreSQL recomputed gross. All three changes are visible without a follow-up SELECT.
You cannot write to a generated column directly. SET gross = 1 is an error. You can still list it in RETURNING.
In PostgreSQL 18 and later you can declare a VIRTUAL generated column. It is computed when read and takes no storage. RETURNING shows its value in the same way.
BEFORE triggers: changes you can see
Because RETURNING reads the row after the write, it shows every change a BEFORE ROW trigger made to NEW. This is the main reason to prefer RETURNING over trusting your own input. The application might otherwise cache note = ' rush ' while the database stores rush.
A BEFORE trigger can also decide that a row should not be written at all. If it returns NULL, PostgreSQL skips that row for that operation. A skipped row produces no RETURNING output:
CREATE FUNCTION invoices_no_zero() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF NEW.net = 0 THEN
RETURN NULL; -- silently skip this row
END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER invoices_no_zero
BEFORE INSERT ON invoices
FOR EACH ROW EXECUTE FUNCTION invoices_no_zero();
INSERT INTO invoices (net) VALUES (0), (25)
RETURNING id, net;Only the row with net = 25.00 comes back, so the statement reports one row instead of two. BEFORE triggers fire in alphabetical order by name, so invoices_no_zero runs before invoices_touch. A skipped row never reaches the second trigger.
AFTER triggers: changes you cannot see
A row-level AFTER trigger runs when the statement finishes. It fires after the row has been written, and after the RETURNING values were taken. Anything it does is invisible to RETURNING.
CREATE TABLE invoice_audit (
audit_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
invoice_id bigint NOT NULL,
old_net numeric(10,2),
new_net numeric(10,2),
changed_at timestamptz NOT NULL DEFAULT now()
);
CREATE FUNCTION invoices_audit() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO invoice_audit (invoice_id, old_net, new_net)
VALUES (NEW.id, OLD.net, NEW.net);
RETURN NULL; -- the return value of an AFTER trigger is ignored
END;
$$;
CREATE TRIGGER invoices_audit
AFTER UPDATE ON invoices
FOR EACH ROW EXECUTE FUNCTION invoices_audit();
UPDATE invoices SET net = 200 WHERE id = 1
RETURNING id, net, gross;
SELECT invoice_id, old_net, new_net FROM invoice_audit;The UPDATE returns id = 1, net = 200.00 and gross = 240.00. The audit row exists, but RETURNING could not include it, because it lives in another table and was created later. Query it separately.
The same holds when an AFTER trigger changes the row you just updated. Suppose it ran UPDATE invoices SET note = 'audited' WHERE id = NEW.id. The statement's RETURNING would still show the old note. A later SELECT would show audited. Treat RETURNING as the state at write time, not the final state at commit.
Triggers on views and other special cases
INSTEAD OFtriggers on a view. The view has no storage, soRETURNINGreports whatever row the trigger function returns. If the trigger returnsNEWunchanged, you see your own input. Have it return the row it actually stored if you want real values.DELETEwithBEFORE DELETEtriggers. The trigger must returnOLD(or another non-null row) to let the delete go ahead.RETURNINGthen shows the deleted row.- Statement-level triggers. They have no per-row
NEW, so they cannot change whatRETURNINGreports. - Rules. If a
DO INSTEADrule rewrites the statement,RETURNINGmay behave differently. Prefer triggers in new code.
Summary table
| Source of a change | Visible in RETURNING? |
|---|---|
| Column default, identity value | Yes |
| Type coercion, such as numeric rounding | Yes |
| `BEFORE ROW` trigger edits to `NEW` | Yes |
| Stored generated column | Yes, computed from the final values |
| `BEFORE` trigger returning `NULL` | The row is skipped and gives no output |
| `AFTER ROW` trigger edits to the same row | No |
| `AFTER` trigger writes to other tables | No |
Exercises
Exercise
A table has a column slug text and a BEFORE INSERT trigger that sets NEW.slug := lower(NEW.slug). You run INSERT INTO pages (slug) VALUES ('Home') RETURNING slug;. What does the statement return, and why?
Show answer
It returns home. The BEFORE trigger changes NEW before the row is written, and RETURNING reads the stored row, so it shows the lowercase value instead of the Home you supplied.
Exercise
An AFTER UPDATE row trigger on invoices sets note = 'audited' on the same row with a second UPDATE. Your statement UPDATE invoices SET net = 10 WHERE id = 1 RETURNING note; runs. Does it return audited? How would you see the final value?
Show answer
No. RETURNING reflects the row as written by your statement, before the AFTER trigger ran, so it shows the earlier note. Run a separate SELECT note FROM invoices WHERE id = 1; after the statement, or move the logic into a BEFORE trigger so that RETURNING includes it.
Exercise
You insert three rows in one statement with RETURNING id, but only two ids come back and no error is raised. Name one cause related to triggers, and one way to find which row was skipped.
Show answer
A BEFORE INSERT row trigger returned NULL for one row, which makes PostgreSQL skip it silently. Include a natural key, such as title, in the RETURNING list and compare it with the values you sent. The missing key identifies the skipped row.