{
    "content": [
        {
            "type": "text",
            "text": "# CREATE_RULE(7) (man)\n\n**Summary:** CREATERULE - define a new rewrite rule\n\n**Synopsis:** CREATE [ OR REPLACE ] RULE name AS ON event\nTO tablename [ WHERE condition ]\nDO [ ALSO | INSTEAD ] { NOTHING | command | ( command ; command ... ) }\nwhere event can be one of:\nSELECT | INSERT | UPDATE | DELETE\n\n## See Also\n\n- ALTERRULE(7)\n- DROPRULE(7)\n- RULE(7)\n\n## Section Outline\n\n- **NAME** (2 lines)\n- **SYNOPSIS** (8 lines)\n- **DESCRIPTION** (47 lines)\n- **PARAMETERS** (34 lines)\n- **NOTES** (40 lines)\n- **COMPATIBILITY** (2 lines)\n- **SEE ALSO** (5 lines)\n\n## Full Content\n\n### NAME\n\nCREATERULE - define a new rewrite rule\n\n### SYNOPSIS\n\nCREATE [ OR REPLACE ] RULE name AS ON event\nTO tablename [ WHERE condition ]\nDO [ ALSO | INSTEAD ] { NOTHING | command | ( command ; command ... ) }\n\nwhere event can be one of:\n\nSELECT | INSERT | UPDATE | DELETE\n\n### DESCRIPTION\n\nCREATE RULE defines a new rule applying to a specified table or view.  CREATE OR REPLACE RULE\nwill either create a new rule, or replace an existing rule of the same name for the same\ntable.\n\nThe PostgreSQL rule system allows one to define an alternative action to be performed on\ninsertions, updates, or deletions in database tables. Roughly speaking, a rule causes\nadditional commands to be executed when a given command on a given table is executed.\nAlternatively, an INSTEAD rule can replace a given command by another, or cause a command not\nto be executed at all. Rules are used to implement SQL views as well. It is important to\nrealize that a rule is really a command transformation mechanism, or command macro. The\ntransformation happens before the execution of the command starts. If you actually want an\noperation that fires independently for each physical row, you probably want to use a trigger,\nnot a rule. More information about the rules system is in Chapter 41.\n\nPresently, ON SELECT rules can only be attached to views. (Attaching one to a table converts\nthe table into a view.) Such a rule must be named \"RETURN\", must be an unconditional INSTEAD\nrule, and must have an action that consists of a single SELECT command. This command defines\nthe visible contents of the view. (The view itself is basically a dummy table with no\nstorage.) It's best to regard such a rule as an implementation detail. While a view can be\nredefined via CREATE OR REPLACE RULE \"RETURN\" AS ..., it's better style to use CREATE OR\nREPLACE VIEW.\n\nYou can create the illusion of an updatable view by defining ON INSERT, ON UPDATE, and ON\nDELETE rules (or any subset of those that's sufficient for your purposes) to replace update\nactions on the view with appropriate updates on other tables. If you want to support INSERT\nRETURNING and so on, then be sure to put a suitable RETURNING clause into each of these\nrules.\n\nThere is a catch if you try to use conditional rules for complex view updates: there must be\nan unconditional INSTEAD rule for each action you wish to allow on the view. If the rule is\nconditional, or is not INSTEAD, then the system will still reject attempts to perform the\nupdate action, because it thinks it might end up trying to perform the action on the dummy\ntable of the view in some cases. If you want to handle all the useful cases in conditional\nrules, add an unconditional DO INSTEAD NOTHING rule to ensure that the system understands it\nwill never be called on to update the dummy table. Then make the conditional rules\nnon-INSTEAD; in the cases where they are applied, they add to the default INSTEAD NOTHING\naction. (This method does not currently work to support RETURNING queries, however.)\n\nNote\nA view that is simple enough to be automatically updatable (see CREATE VIEW\n(CREATEVIEW(7))) does not require a user-created rule in order to be updatable. While\nyou can create an explicit rule anyway, the automatic update transformation will\ngenerally outperform an explicit rule.\n\nAnother alternative worth considering is to use INSTEAD OF triggers (see CREATE TRIGGER\n(CREATETRIGGER(7))) in place of rules.\n\n### PARAMETERS\n\nname\nThe name of a rule to create. This must be distinct from the name of any other rule for\nthe same table. Multiple rules on the same table and same event type are applied in\nalphabetical name order.\n\nevent\nThe event is one of SELECT, INSERT, UPDATE, or DELETE. Note that an INSERT containing an\nON CONFLICT clause cannot be used on tables that have either INSERT or UPDATE rules.\nConsider using an updatable view instead.\n\ntablename\nThe name (optionally schema-qualified) of the table or view the rule applies to.\n\ncondition\nAny SQL conditional expression (returning boolean). The condition expression cannot refer\nto any tables except NEW and OLD, and cannot contain aggregate functions.\n\nINSTEAD\nINSTEAD indicates that the commands should be executed instead of the original command.\n\nALSO\nALSO indicates that the commands should be executed in addition to the original command.\n\nIf neither ALSO nor INSTEAD is specified, ALSO is the default.\n\ncommand\nThe command or commands that make up the rule action. Valid commands are SELECT, INSERT,\nUPDATE, DELETE, or NOTIFY.\n\nWithin condition and command, the special table names NEW and OLD can be used to refer to\nvalues in the referenced table.  NEW is valid in ON INSERT and ON UPDATE rules to refer to\nthe new row being inserted or updated.  OLD is valid in ON UPDATE and ON DELETE rules to\nrefer to the existing row being updated or deleted.\n\n### NOTES\n\nYou must be the owner of a table to create or change rules for it.\n\nIn a rule for INSERT, UPDATE, or DELETE on a view, you can add a RETURNING clause that emits\nthe view's columns. This clause will be used to compute the outputs if the rule is triggered\nby an INSERT RETURNING, UPDATE RETURNING, or DELETE RETURNING command respectively. When the\nrule is triggered by a command without RETURNING, the rule's RETURNING clause will be\nignored. The current implementation allows only unconditional INSTEAD rules to contain\nRETURNING; furthermore there can be at most one RETURNING clause among all the rules for the\nsame event. (This ensures that there is only one candidate RETURNING clause to be used to\ncompute the results.)  RETURNING queries on the view will be rejected if there is no\nRETURNING clause in any available rule.\n\nIt is very important to take care to avoid circular rules. For example, though each of the\nfollowing two rule definitions are accepted by PostgreSQL, the SELECT command would cause\nPostgreSQL to report an error because of recursive expansion of a rule:\n\nCREATE RULE \"RETURN\" AS\nON SELECT TO t1\nDO INSTEAD\nSELECT * FROM t2;\n\nCREATE RULE \"RETURN\" AS\nON SELECT TO t2\nDO INSTEAD\nSELECT * FROM t1;\n\nSELECT * FROM t1;\n\nPresently, if a rule action contains a NOTIFY command, the NOTIFY command will be executed\nunconditionally, that is, the NOTIFY will be issued even if there are not any rows that the\nrule should apply to. For example, in:\n\nCREATE RULE notifyme AS ON UPDATE TO mytable DO ALSO NOTIFY mytable;\n\nUPDATE mytable SET name = 'foo' WHERE id = 42;\n\none NOTIFY event will be sent during the UPDATE, whether or not there are any rows that match\nthe condition id = 42. This is an implementation restriction that might be fixed in future\nreleases.\n\n### COMPATIBILITY\n\nCREATE RULE is a PostgreSQL language extension, as is the entire query rewrite system.\n\n### SEE ALSO\n\nALTER RULE (ALTERRULE(7)), DROP RULE (DROPRULE(7))\n\n\n\nPostgreSQL 14.23                                2026                                  CREATE RULE(7)\n\n"
        }
    ],
    "structuredContent": {
        "command": "CREATE_RULE",
        "section": "7",
        "mode": "man",
        "summary": "CREATERULE - define a new rewrite rule",
        "synopsis": "CREATE [ OR REPLACE ] RULE name AS ON event\nTO tablename [ WHERE condition ]\nDO [ ALSO | INSTEAD ] { NOTHING | command | ( command ; command ... ) }\nwhere event can be one of:\nSELECT | INSERT | UPDATE | DELETE",
        "flags": [],
        "examples": [],
        "see_also": [
            {
                "name": "ALTERRULE",
                "section": "7",
                "url": "https://www.chedong.com/phpMan.php/man/ALTERRULE/7/json"
            },
            {
                "name": "DROPRULE",
                "section": "7",
                "url": "https://www.chedong.com/phpMan.php/man/DROPRULE/7/json"
            },
            {
                "name": "RULE",
                "section": "7",
                "url": "https://www.chedong.com/phpMan.php/man/RULE/7/json"
            }
        ],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "SYNOPSIS",
                "lines": 8,
                "subsections": []
            },
            {
                "name": "DESCRIPTION",
                "lines": 47,
                "subsections": []
            },
            {
                "name": "PARAMETERS",
                "lines": 34,
                "subsections": []
            },
            {
                "name": "NOTES",
                "lines": 40,
                "subsections": []
            },
            {
                "name": "COMPATIBILITY",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "SEE ALSO",
                "lines": 5,
                "subsections": []
            }
        ]
    }
}