Sub topic 10
Defaults, generated columns and triggers: what RETURNING reflects
Assume you know basic INSERT, UPDATE, and DELETE, primary keys, column defaults, and how to run SQL in psql or another PostgreSQL client.
RETURNING reports the row version produced by the data-changing statement. That includes values supplied by defaults, stored generated columns, and changes made by BEFORE triggers. It does not automatically return rows written to another table by an AFTER trigger.
Defaults are included automatically
A default expression runs when an INSERT omits that column or uses the keyword DEFAULT. The value is then available in the RETURNING result.
For example, an identity column generates a key, while now() supplies a timestamp:
CREATE TABLE tasks (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
status text NOT NULL DEFAULT 'open',
created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO tasks (title)
VALUES ('Write report')
RETURNING id, title, status, created_at;The result contains the generated id, the default status, and the timestamp. This avoids a second SELECT.
Defaults apply to inserted rows. An UPDATE does not reapply a default to a column that is left out of its SET list. The existing value remains unchanged.
Generated columns are calculated before RETURNING
A stored generated column is calculated from other columns. You cannot normally assign its value directly. PostgreSQL calculates it after applying BEFORE row triggers, so RETURNING can show the final generated value.
DROP TABLE IF EXISTS invoice_audit, invoice_items CASCADE;
CREATE TABLE invoice_items (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
description text NOT NULL DEFAULT 'Unnamed',
quantity integer NOT NULL DEFAULT 1,
unit_price numeric(10, 2) NOT NULL,
total numeric(12, 2)
GENERATED ALWAYS AS (quantity * unit_price) STORED,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE invoice_audit (
invoice_id bigint NOT NULL,
total numeric(12, 2) NOT NULL,
recorded_at timestamptz NOT NULL DEFAULT now()
);
CREATE FUNCTION normalize_invoice_item()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
NEW.description := COALESCE(NULLIF(btrim(NEW.description), ''), 'Unnamed');
NEW.quantity := GREATEST(COALESCE(NEW.quantity, 1), 1);
RETURN NEW;
END;
$$;
CREATE FUNCTION audit_invoice_item()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
INSERT INTO invoice_audit (invoice_id, total)
VALUES (NEW.id, NEW.total);
RETURN NEW;
END;
$$;
CREATE TRIGGER invoice_item_normalize
BEFORE INSERT OR UPDATE ON invoice_items
FOR EACH ROW EXECUTE FUNCTION normalize_invoice_item();
CREATE TRIGGER invoice_item_audit
AFTER INSERT OR UPDATE ON invoice_items
FOR EACH ROW EXECUTE FUNCTION audit_invoice_item();
INSERT INTO invoice_items (description, quantity, unit_price)
VALUES (' Support ', 0, 25.00)
RETURNING id, description, quantity, unit_price, total, created_at;The returned row has description = 'Support', quantity = 1, and total = 25.00. The BEFORE trigger changed the input before PostgreSQL calculated total.
The AFTER trigger also inserted a row into invoice_audit, but that audit row is not part of this RETURNING result. To read it, issue a separate SELECT, or design a data-modifying CTE when the operation needs to pass rows between statements.
What triggers can and cannot change
A BEFORE trigger can assign to NEW. Those assignments are visible through RETURNING.
An AFTER trigger runs after the row has been stored. It can insert audit records, send notifications, or update other tables. Its side effects are not merged into the row returned by the original statement. If another trigger changes a different table, query that table separately.
A trigger can also reject a row by raising an error. In that case, the statement fails and produces no RETURNING result.
Common mistakes
- Expecting an
UPDATEto restore a default when a column is omitted. - Trying to assign a value directly to a generated column.
- Assuming an
AFTERtrigger's audit row appears in the original result. - Forgetting that a
BEFOREtrigger may normalize, replace, or reject input. - Assuming
RETURNINGproduces a row when the statement affects zero rows. It produces zero rows in that case.
Exercise
An INSERT omits a column with a default, and a BEFORE trigger changes another column used by a stored generated column. What values does RETURNING show?
Show answer
It shows the defaulted value, the value after the BEFORE trigger, and the generated column recalculated from that final input.