CREATE_RULE(7pg15)

πŸ“¦ version 15.19, in opensuse-leap 16.0

πŸ¦‹ CREATE RULE (7) β€” the PostgreSQL 15.19 glow-up guide πŸ¦‹

okay bestie, sit down, hydrate, and let me tell you about CREATE RULE β€” like, this is the page from the PostgreSQL 15.19 docs and we're gonna make it make sense πŸ’…


✨ NAME ✨

CREATE_RULE β€” define a new rewrite rule. yes that's the whole name, it's giving minimalist icon πŸ’–


πŸŽ€ SYNOPSIS πŸŽ€

CREATE [ OR REPLACE ] RULE name AS ON event
    TO table_name [ WHERE condition ]
    DO [ ALSO | INSTEAD ] { NOTHING | command | ( command ; command ... ) }

and event can be literally one of these, no substitutions:

SELECT | INSERT | UPDATE | DELETE

πŸ’œ DESCRIPTION πŸ’œ

so CREATE RULE defines a brand-new rule that applies to a specific table or view. and CREATE OR REPLACE RULE? that's the "glow up an existing one" option β€” it either makes a new rule or swaps out an existing rule with the same name on the same table. no cap 🫢

the PostgreSQL rule system lets you define an alternative action to be performed on insertions, updates, or deletions in database tables. roughly speaking (their words, not mine, but slay), a rule makes extra commands run whenever a given command on a given table runs. alternatively an INSTEAD rule can straight-up replace a given command with another one, or make a command not execute at all. rules are also how SQL views get implemented, iykyk ✨

and here's the thing you have to internalize, bestie: a rule is really a command transformation mechanism, or command macro. the transformation happens before the execution of the command starts. so if you actually want an operation that fires independently for each physical row, you probably want a trigger, not a rule. periodt. more info about the rules system lives in Chapter 41 πŸ“š

so right now, ON SELECT rules can only be attached to views. (attaching one to a table converts the table into a view β€” yes, really, it just manifests the transformation πŸ™ˆ) such a rule must be:

  • named "_RETURN"
  • an unconditional INSTEAD rule
  • have an action that consists of a single SELECT command

that command defines the visible contents of the view. (the view itself is basically a dummy table with no storage, it's giving empty shell energy πŸ’€) it's best to regard such a rule as an implementation detail. while a view can be redefined via CREATE OR REPLACE RULE "_RETURN" AS ..., it's better style to use CREATE OR REPLACE VIEW. do with that what you will πŸ’…

you can create the illusion of an updatable view by defining ON INSERT, ON UPDATE, and ON DELETE rules (or any subset of those that's sufficient for your purposes) to replace update actions on the view with appropriate updates on other tables. and if you want to support INSERT RETURNING and so on, then be sure to put a suitable RETURNING clause into each of these rules. don't forget it, bestie, it's literally free πŸ”₯

now β€” there is a catch if you try to use conditional rules for complex view updates 😭 there must be an unconditional INSTEAD rule for each action you wish to allow on the view. if the rule is conditional, or is not INSTEAD, then the system will still reject attempts to perform the update action, because it thinks it might end up trying to perform the action on the dummy table of the view in some cases. so if you want to handle all the useful cases in conditional rules, add an unconditional DO INSTEAD NOTHING rule to ensure that the system understands it will never be called on to update the dummy table. then make the conditional rules non-INSTEAD; in the cases where they are applied, they add to the default INSTEAD NOTHING action. (this method does not currently work to support RETURNING queries, however β€” sad but true πŸ₯²)

Note 🫢 a view that is simple enough to be automatically updatable (see CREATE VIEW (CREATE_VIEW(7))) does not require a user-created rule in order to be updatable. while you can create an explicit rule anyway, the automatic update transformation will generally outperform an explicit rule. so like, you can, but why 😭 another alternative worth considering is to use INSTEAD OF triggers (see CREATE TRIGGER (CREATE_TRIGGER(7))) in place of rules. πŸ‘‘

🌸 PARAMETERS 🌸

  • name β€” the name of a rule to create. this must be distinct from the name of any other rule for the same table. multiple rules on the same table and same event type are applied in alphabetical name order (so yeah, your naming game matters, bestie πŸ”€).
  • event β€” the event is one of SELECT, INSERT, UPDATE, or DELETE. note that an INSERT containing an ON CONFLICT clause cannot be used on tables that have either INSERT or UPDATE rules. consider using an updatable view instead 🫠
  • table_name β€” the name (optionally schema-qualified) of the table or view the rule applies to.
  • condition β€” any SQL conditional expression (returning boolean). the condition expression cannot refer to any tables except NEW and OLD, and cannot contain aggregate functions. that's a hard no 🚫
  • INSTEAD β€” INSTEAD indicates that the commands should be executed instead of the original command.
  • ALSO β€” ALSO indicates that the commands should be executed in addition to the original command. if neither ALSO nor INSTEAD is specified, ALSO is the default. good to know πŸ’–
  • command β€” the command or commands that make up the rule action. valid commands are SELECT, INSERT, UPDATE, DELETE, or NOTIFY.

and within condition and command, the special table names NEW and OLD can be used to refer to values in the referenced table. NEW is valid in ON INSERT and ON UPDATE rules to refer to the new row being inserted or updated. OLD is valid in ON UPDATE and ON DELETE rules to refer to the existing row being updated or deleted. iconic, honestly ⭐


πŸ’€ NOTES πŸ’€

you must be the owner of a table to create or change rules for it. no ownership, no rules, that's the vibe check πŸ‘‘

in a rule for INSERT, UPDATE, or DELETE on a view, you can add a RETURNING clause that emits the view's columns. this clause will be used to compute the outputs if the rule is triggered by an INSERT RETURNING, UPDATE RETURNING, or DELETE RETURNING command respectively. when the rule is triggered by a command without RETURNING, the rule's RETURNING clause will be ignored. the current implementation allows only unconditional INSTEAD rules to contain RETURNING; furthermore there can be at most one RETURNING clause among all the rules for the same event. (this ensures that there is only one candidate RETURNING clause to be used to compute the results.) RETURNING queries on the view will be rejected if there is no RETURNING clause in any available rule. yeah. brutal but fair 😭

it is very important to take care to avoid circular rules. for example, though each of the following two rule definitions are accepted by PostgreSQL, the SELECT command would cause PostgreSQL to report an error because of recursive expansion of a rule:

CREATE RULE "_RETURN" AS
    ON SELECT TO t1
    DO INSTEAD
        SELECT * FROM t2;

CREATE RULE "_RETURN" AS
    ON SELECT TO t2
    DO INSTEAD
        SELECT * FROM t1;

SELECT * FROM t1;

see how that just eats itself πŸŒ€ don't do that.

presently, if a rule action contains a NOTIFY command, the NOTIFY command will be executed unconditionally β€” that is, the NOTIFY will be issued even if there are not any rows that the rule should apply to. for example, in:

CREATE RULE notify_me AS ON UPDATE TO mytable DO ALSO NOTIFY mytable;

UPDATE mytable SET name = 'foo' WHERE id = 42;

one NOTIFY event will be sent during the UPDATE, whether or not there are any rows that match the condition id = 42. this is an implementation restriction that might be fixed in future releases. (so like, it's not you, it's the implementation πŸ₯²)


🌈 COMPATIBILITY 🌈

CREATE RULE is a PostgreSQL language extension β€” as is the entire query rewrite system. so yeah, it's a postgres thing, it's giving main character energy πŸ‘‘


🧚 SEE ALSO 🧚

go read those next, bestie, i believe in you πŸ’œ


and that's the whole page!! sign-off time: this was the PostgreSQL 15.19 documentation, dated 2026, for CREATE RULE(7) β€” mwah, go write some rules, and remember: transform before execution, no circular nonsense, and always name your stuff so the alphabetical ordering doesn't betray you πŸ’…βœ¨πŸŽ€

πŸ“¦ where this page comes from