CREATE_RULE(7pg15)
π¦ 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
INSTEADrule - have an action that consists of a single
SELECTcommand
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 (seeCREATE 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 useINSTEAD OFtriggers (seeCREATE 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 ofSELECT,INSERT,UPDATE, orDELETE. note that anINSERTcontaining anON CONFLICTclause cannot be used on tables that have eitherINSERTorUPDATErules. 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 exceptNEWandOLD, and cannot contain aggregate functions. that's a hard no π«INSTEADβINSTEADindicates that the commands should be executed instead of the original command.ALSOβALSOindicates that the commands should be executed in addition to the original command. if neitherALSOnorINSTEADis specified,ALSOis the default. good to know πcommandβ the command or commands that make up the rule action. valid commands areSELECT,INSERT,UPDATE,DELETE, orNOTIFY.
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 π§
ALTER RULE(ALTER_RULE(7))DROP RULE(DROP_RULE(7))
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
- opensuse-leap 16.0: postgresql15 15.19-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql15 15.19-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql15 15.19-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql15 15.19-160000.1.1 Β· PostgreSQL
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms