Instead Of Trigger Makes View Writable
A filtered view is read-only until an INSTEAD OF trigger routes inserts into the base table, stamping the hidden column the view never exposes.
Code
CREATE TABLE authors (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
published boolean NOT NULL DEFAULT false
);
CREATE VIEW published_authors AS
SELECT id, name FROM authors WHERE published;
-- plain views reject writes; an INSTEAD OF trigger makes the filtered view
-- writable by handing each row to a routing function
CREATE OR REPLACE FUNCTION publish_author()
RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO authors (name, published)
VALUES (NEW.name, true)
RETURNING id INTO NEW.id;
RETURN NEW;
END;
$$;
CREATE TRIGGER published_authors_insert
INSTEAD OF INSERT ON published_authors
FOR EACH ROW EXECUTE FUNCTION publish_author();
-- the write lands in the base table with published forced to true
INSERT INTO published_authors (name) VALUES ('Ada Lovelace');
SELECT id, name, published FROM authors;
SELECT id, name FROM published_authors;How the pieces connect — Instead Of Trigger Makes View Writable
What runs here is SELECT / INSERT / CREATE — authors, new.id and published_authors are the objects involved.
The pieces that do the work: a WHERE clause constraining which rows the statement operates on; a RETURNING clause that hands the affected rows back to the caller; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Putting it to use
The authors table is the working surface here.
Core lines
CREATE VIEW published_authors AS
SELECT id, name FROM authors WHERE published;
CREATE OR REPLACE FUNCTION publish_author()
RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO authors (name, published)
VALUES (NEW.name, true)
RETURNING id INTO NEW.id;
RETURN NEW;
END;
$$;
CREATE TRIGGER published_authors_insert
INSTEAD OF INSERT ON published_authors
FOR EACH ROW EXECUTE FUNCTION publish_author();
Interactive Tools for This Topic
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What relations does the SQL touch?
- `authors`, `new.id`, `published_authors`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.