{
    "mode": "man",
    "parameter": "CREATE_TRIGGER",
    "section": "7",
    "url": "https://www.chedong.com/phpMan.php/man/CREATE_TRIGGER/7/json",
    "generated": "2026-06-03T01:48:18Z",
    "synopsis": "CREATE [ OR REPLACE ] [ CONSTRAINT ] TRIGGER name { BEFORE | AFTER | INSTEAD OF } { event [ OR ... ] }\nON tablename\n[ FROM referencedtablename ]\n[ NOT DEFERRABLE | [ DEFERRABLE ] [ INITIALLY IMMEDIATE | INITIALLY DEFERRED ] ]\n[ REFERENCING { { OLD | NEW } TABLE [ AS ] transitionrelationname } [ ... ] ]\n[ FOR [ EACH ] { ROW | STATEMENT } ]\n[ WHEN ( condition ) ]\nEXECUTE { FUNCTION | PROCEDURE } functionname ( arguments )\nwhere event can be one of:\nINSERT\nUPDATE [ OF columnname [, ... ] ]\nDELETE\nTRUNCATE",
    "sections": {
        "NAME": {
            "content": "CREATETRIGGER - define a new trigger\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "CREATE [ OR REPLACE ] [ CONSTRAINT ] TRIGGER name { BEFORE | AFTER | INSTEAD OF } { event [ OR ... ] }\nON tablename\n[ FROM referencedtablename ]\n[ NOT DEFERRABLE | [ DEFERRABLE ] [ INITIALLY IMMEDIATE | INITIALLY DEFERRED ] ]\n[ REFERENCING { { OLD | NEW } TABLE [ AS ] transitionrelationname } [ ... ] ]\n[ FOR [ EACH ] { ROW | STATEMENT } ]\n[ WHEN ( condition ) ]\nEXECUTE { FUNCTION | PROCEDURE } functionname ( arguments )\n\nwhere event can be one of:\n\nINSERT\nUPDATE [ OF columnname [, ... ] ]\nDELETE\nTRUNCATE\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "CREATE TRIGGER creates a new trigger.  CREATE OR REPLACE TRIGGER will either create a new\ntrigger, or replace an existing trigger. The trigger will be associated with the specified\ntable, view, or foreign table and will execute the specified function functionname when\ncertain operations are performed on that table.\n\nTo replace the current definition of an existing trigger, use CREATE OR REPLACE TRIGGER,\nspecifying the existing trigger's name and parent table. All other properties are replaced.\n\nThe trigger can be specified to fire before the operation is attempted on a row (before\nconstraints are checked and the INSERT, UPDATE, or DELETE is attempted); or after the\noperation has completed (after constraints are checked and the INSERT, UPDATE, or DELETE has\ncompleted); or instead of the operation (in the case of inserts, updates or deletes on a\nview). If the trigger fires before or instead of the event, the trigger can skip the\noperation for the current row, or change the row being inserted (for INSERT and UPDATE\noperations only). If the trigger fires after the event, all changes, including the effects of\nother triggers, are “visible” to the trigger.\n\nA trigger that is marked FOR EACH ROW is called once for every row that the operation\nmodifies. For example, a DELETE that affects 10 rows will cause any ON DELETE triggers on the\ntarget relation to be called 10 separate times, once for each deleted row. In contrast, a\ntrigger that is marked FOR EACH STATEMENT only executes once for any given operation,\nregardless of how many rows it modifies (in particular, an operation that modifies zero rows\nwill still result in the execution of any applicable FOR EACH STATEMENT triggers).\n\nTriggers that are specified to fire INSTEAD OF the trigger event must be marked FOR EACH ROW,\nand can only be defined on views.  BEFORE and AFTER triggers on a view must be marked as FOR\nEACH STATEMENT.\n\nIn addition, triggers may be defined to fire for TRUNCATE, though only FOR EACH STATEMENT.\n\nThe following table summarizes which types of triggers may be used on tables, views, and\nforeign tables:\n\n┌───────────┬──────────────────────┬────────────────────┬────────────────────┐\n│When       │ Event                │ Row-level          │ Statement-level    │\n├───────────┼──────────────────────┼────────────────────┼────────────────────┤\n│           │ INSERT/UPDATE/DELETE │ Tables and foreign │ Tables, views, and │\n│  BEFORE   │                      │ tables             │ foreign tables     │\n│           ├──────────────────────┼────────────────────┼────────────────────┤\n│           │       TRUNCATE       │         —          │       Tables       │\n├───────────┼──────────────────────┼────────────────────┼────────────────────┤\n│           │ INSERT/UPDATE/DELETE │ Tables and foreign │ Tables, views, and │\n│  AFTER    │                      │ tables             │ foreign tables     │\n│           ├──────────────────────┼────────────────────┼────────────────────┤\n│           │       TRUNCATE       │         —          │       Tables       │\n├───────────┼──────────────────────┼────────────────────┼────────────────────┤\n│           │ INSERT/UPDATE/DELETE │       Views        │         —          │\n│INSTEAD OF ├──────────────────────┼────────────────────┼────────────────────┤\n│           │       TRUNCATE       │         —          │         —          │\n└───────────┴──────────────────────┴────────────────────┴────────────────────┘\n\nAlso, a trigger definition can specify a Boolean WHEN condition, which will be tested to see\nwhether the trigger should be fired. In row-level triggers the WHEN condition can examine the\nold and/or new values of columns of the row. Statement-level triggers can also have WHEN\nconditions, although the feature is not so useful for them since the condition cannot refer\nto any values in the table.\n\nIf multiple triggers of the same kind are defined for the same event, they will be fired in\nalphabetical order by name.\n\nWhen the CONSTRAINT option is specified, this command creates a constraint trigger. This is\nthe same as a regular trigger except that the timing of the trigger firing can be adjusted\nusing SET CONSTRAINTS. Constraint triggers must be AFTER ROW triggers on plain tables (not\nforeign tables). They can be fired either at the end of the statement causing the triggering\nevent, or at the end of the containing transaction; in the latter case they are said to be\ndeferred. A pending deferred-trigger firing can also be forced to happen immediately by using\nSET CONSTRAINTS. Constraint triggers are expected to raise an exception when the constraints\nthey implement are violated.\n\nThe REFERENCING option enables collection of transition relations, which are row sets that\ninclude all of the rows inserted, deleted, or modified by the current SQL statement. This\nfeature lets the trigger see a global view of what the statement did, not just one row at a\ntime. This option is only allowed for an AFTER trigger on a plain table (not a foreign\ntable). The trigger should not be a constraint trigger. Also, if the trigger is an UPDATE\ntrigger, it must not specify a columnname list when using this option.  OLD TABLE may only\nbe specified once, and only for a trigger that can fire on UPDATE or DELETE; it creates a\ntransition relation containing the before-images of all rows updated or deleted by the\nstatement. Similarly, NEW TABLE may only be specified once, and only for a trigger that can\nfire on UPDATE or INSERT; it creates a transition relation containing the after-images of all\nrows updated or inserted by the statement.\n\nSELECT does not modify any rows so you cannot create SELECT triggers. Rules and views may\nprovide workable solutions to problems that seem to need SELECT triggers.\n\nRefer to Chapter 39 for more information about triggers.\n",
            "subsections": []
        },
        "PARAMETERS": {
            "content": "name\nThe name to give the new trigger. This must be distinct from the name of any other\ntrigger for the same table. The name cannot be schema-qualified — the trigger inherits\nthe schema of its table. For a constraint trigger, this is also the name to use when\nmodifying the trigger's behavior using SET CONSTRAINTS.\n\nBEFORE\nAFTER\nINSTEAD OF\nDetermines whether the function is called before, after, or instead of the event. A\nconstraint trigger can only be specified as AFTER.\n\nevent\nOne of INSERT, UPDATE, DELETE, or TRUNCATE; this specifies the event that will fire the\ntrigger. Multiple events can be specified using OR, except when transition relations are\nrequested.\n\nFor UPDATE events, it is possible to specify a list of columns using this syntax:\n\nUPDATE OF columnname1 [, columnname2 ... ]\n\nThe trigger will only fire if at least one of the listed columns is mentioned as a target\nof the UPDATE command or if one of the listed columns is a generated column that depends\non a column that is the target of the UPDATE.\n\nINSTEAD OF UPDATE events do not allow a list of columns. A column list cannot be\nspecified when requesting transition relations, either.\n\ntablename\nThe name (optionally schema-qualified) of the table, view, or foreign table the trigger\nis for.\n\nreferencedtablename\nThe (possibly schema-qualified) name of another table referenced by the constraint. This\noption is used for foreign-key constraints and is not recommended for general use. This\ncan only be specified for constraint triggers.\n\nDEFERRABLE\nNOT DEFERRABLE\nINITIALLY IMMEDIATE\nINITIALLY DEFERRED\nThe default timing of the trigger. See the CREATE TABLE (CREATETABLE(7)) documentation\nfor details of these constraint options. This can only be specified for constraint\ntriggers.\n\nREFERENCING\nThis keyword immediately precedes the declaration of one or two relation names that\nprovide access to the transition relations of the triggering statement.\n\nOLD TABLE\nNEW TABLE\nThis clause indicates whether the following relation name is for the before-image\ntransition relation or the after-image transition relation.\n\ntransitionrelationname\nThe (unqualified) name to be used within the trigger for this transition relation.\n\nFOR EACH ROW\nFOR EACH STATEMENT\nThis specifies whether the trigger function should be fired once for every row affected\nby the trigger event, or just once per SQL statement. If neither is specified, FOR EACH\nSTATEMENT is the default. Constraint triggers can only be specified FOR EACH ROW.\n\ncondition\nA Boolean expression that determines whether the trigger function will actually be\nexecuted. If WHEN is specified, the function will only be called if the condition returns\ntrue. In FOR EACH ROW triggers, the WHEN condition can refer to columns of the old and/or\nnew row values by writing OLD.columnname or NEW.columnname respectively. Of course,\nINSERT triggers cannot refer to OLD and DELETE triggers cannot refer to NEW.\n\nINSTEAD OF triggers do not support WHEN conditions.\n\nCurrently, WHEN expressions cannot contain subqueries.\n\nNote that for constraint triggers, evaluation of the WHEN condition is not deferred, but\noccurs immediately after the row update operation is performed. If the condition does not\nevaluate to true then the trigger is not queued for deferred execution.\n\nfunctionname\nA user-supplied function that is declared as taking no arguments and returning type\ntrigger, which is executed when the trigger fires.\n\nIn the syntax of CREATE TRIGGER, the keywords FUNCTION and PROCEDURE are equivalent, but\nthe referenced function must in any case be a function, not a procedure. The use of the\nkeyword PROCEDURE here is historical and deprecated.\n\narguments\nAn optional comma-separated list of arguments to be provided to the function when the\ntrigger is executed. The arguments are literal string constants. Simple names and numeric\nconstants can be written here, too, but they will all be converted to strings. Please\ncheck the description of the implementation language of the trigger function to find out\nhow these arguments can be accessed within the function; it might be different from\nnormal function arguments.\n",
            "subsections": []
        },
        "NOTES": {
            "content": "To create or replace a trigger on a table, the user must have the TRIGGER privilege on the\ntable. The user must also have EXECUTE privilege on the trigger function.\n\nUse DROP TRIGGER to remove a trigger.\n\nCreating a row-level trigger on a partitioned table will cause an identical “clone” trigger\nto be created on each of its existing partitions; and any partitions created or attached\nlater will have an identical trigger, too. If there is a conflictingly-named trigger on a\nchild partition already, an error occurs unless CREATE OR REPLACE TRIGGER is used, in which\ncase that trigger is replaced with a clone trigger. When a partition is detached from its\nparent, its clone triggers are removed.\n\nA column-specific trigger (one defined using the UPDATE OF columnname syntax) will fire when\nany of its columns are listed as targets in the UPDATE command's SET list. It is possible for\na column's value to change even when the trigger is not fired, because changes made to the\nrow's contents by BEFORE UPDATE triggers are not considered. Conversely, a command such as\nUPDATE ... SET x = x ...  will fire a trigger on column x, even though the column's value did\nnot change.\n\nIn a BEFORE trigger, the WHEN condition is evaluated just before the function is or would be\nexecuted, so using WHEN is not materially different from testing the same condition at the\nbeginning of the trigger function. Note in particular that the NEW row seen by the condition\nis the current value, as possibly modified by earlier triggers. Also, a BEFORE trigger's WHEN\ncondition is not allowed to examine the system columns of the NEW row (such as ctid), because\nthose won't have been set yet.\n\nIn an AFTER trigger, the WHEN condition is evaluated just after the row update occurs, and it\ndetermines whether an event is queued to fire the trigger at the end of statement. So when an\nAFTER trigger's WHEN condition does not return true, it is not necessary to queue an event\nnor to re-fetch the row at end of statement. This can result in significant speedups in\nstatements that modify many rows, if the trigger only needs to be fired for a few of the\nrows.\n\nIn some cases it is possible for a single SQL command to fire more than one kind of trigger.\nFor instance an INSERT with an ON CONFLICT DO UPDATE clause may cause both insert and update\noperations, so it will fire both kinds of triggers as needed. The transition relations\nsupplied to triggers are specific to their event type; thus an INSERT trigger will see only\nthe inserted rows, while an UPDATE trigger will see only the updated rows.\n\nRow updates or deletions caused by foreign-key enforcement actions, such as ON UPDATE CASCADE\nor ON DELETE SET NULL, are treated as part of the SQL command that caused them (note that\nsuch actions are never deferred). Relevant triggers on the affected table will be fired, so\nthat this provides another way in which an SQL command might fire triggers not directly\nmatching its type. In simple cases, triggers that request transition relations will see all\nchanges caused in their table by a single original SQL command as a single transition\nrelation. However, there are cases in which the presence of an AFTER ROW trigger that\nrequests transition relations will cause the foreign-key enforcement actions triggered by a\nsingle SQL command to be split into multiple steps, each with its own transition relation(s).\nIn such cases, any statement-level triggers that are present will be fired once per creation\nof a transition relation set, ensuring that the triggers see each affected row in a\ntransition relation once and only once.\n\nStatement-level triggers on a view are fired only if the action on the view is handled by a\nrow-level INSTEAD OF trigger. If the action is handled by an INSTEAD rule, then whatever\nstatements are emitted by the rule are executed in place of the original statement naming the\nview, so that the triggers that will be fired are those on tables named in the replacement\nstatements. Similarly, if the view is automatically updatable, then the action is handled by\nautomatically rewriting the statement into an action on the view's base table, so that the\nbase table's statement-level triggers are the ones that are fired.\n\nModifying a partitioned table or a table with inheritance children fires statement-level\ntriggers attached to the explicitly named table, but not statement-level triggers for its\npartitions or child tables. In contrast, row-level triggers are fired on the rows in affected\npartitions or child tables, even if they are not explicitly named in the query. If a\nstatement-level trigger has been defined with transition relations named by a REFERENCING\nclause, then before and after images of rows are visible from all affected partitions or\nchild tables. In the case of inheritance children, the row images include only columns that\nare present in the table that the trigger is attached to.\n\nCurrently, row-level triggers with transition relations cannot be defined on partitions or\ninheritance child tables. Also, triggers on partitioned tables may not be INSTEAD OF.\n\nCurrently, the OR REPLACE option is not supported for constraint triggers.\n\nReplacing an existing trigger within a transaction that has already performed updating\nactions on the trigger's table is not recommended. Trigger firing decisions, or portions of\nfiring decisions, that have already been made will not be reconsidered, so the effects could\nbe surprising.\n\nThere are a few built-in trigger functions that can be used to solve common problems without\nhaving to write your own trigger code; see Section 9.28.\n",
            "subsections": []
        },
        "EXAMPLES": {
            "content": "Execute the function checkaccountupdate whenever a row of the table accounts is about to be\nupdated:\n\nCREATE TRIGGER checkupdate\nBEFORE UPDATE ON accounts\nFOR EACH ROW\nEXECUTE FUNCTION checkaccountupdate();\n\nModify that trigger definition to only execute the function if column balance is specified as\na target in the UPDATE command:\n\nCREATE OR REPLACE TRIGGER checkupdate\nBEFORE UPDATE OF balance ON accounts\nFOR EACH ROW\nEXECUTE FUNCTION checkaccountupdate();\n\nThis form only executes the function if column balance has in fact changed value:\n\nCREATE TRIGGER checkupdate\nBEFORE UPDATE ON accounts\nFOR EACH ROW\nWHEN (OLD.balance IS DISTINCT FROM NEW.balance)\nEXECUTE FUNCTION checkaccountupdate();\n\nCall a function to log updates of accounts, but only if something changed:\n\nCREATE TRIGGER logupdate\nAFTER UPDATE ON accounts\nFOR EACH ROW\nWHEN (OLD.* IS DISTINCT FROM NEW.*)\nEXECUTE FUNCTION logaccountupdate();\n\nExecute the function viewinsertrow for each row to insert rows into the tables underlying a\nview:\n\nCREATE TRIGGER viewinsert\nINSTEAD OF INSERT ON myview\nFOR EACH ROW\nEXECUTE FUNCTION viewinsertrow();\n\nExecute the function checktransferbalancestozero for each statement to confirm that the\ntransfer rows offset to a net of zero:\n\nCREATE TRIGGER transferinsert\nAFTER INSERT ON transfer\nREFERENCING NEW TABLE AS inserted\nFOR EACH STATEMENT\nEXECUTE FUNCTION checktransferbalancestozero();\n\nExecute the function checkmatchingpairs for each row to confirm that changes are made to\nmatching pairs at the same time (by the same statement):\n\nCREATE TRIGGER paireditemsupdate\nAFTER UPDATE ON paireditems\nREFERENCING NEW TABLE AS newtab OLD TABLE AS oldtab\nFOR EACH ROW\nEXECUTE FUNCTION checkmatchingpairs();\n\nSection 39.4 contains a complete example of a trigger function written in C.\n",
            "subsections": []
        },
        "COMPATIBILITY": {
            "content": "The CREATE TRIGGER statement in PostgreSQL implements a subset of the SQL standard. The\nfollowing functionalities are currently missing:\n\n•   While transition table names for AFTER triggers are specified using the REFERENCING\nclause in the standard way, the row variables used in FOR EACH ROW triggers may not be\nspecified in a REFERENCING clause. They are available in a manner that is dependent on\nthe language in which the trigger function is written, but is fixed for any one language.\nSome languages effectively behave as though there is a REFERENCING clause containing OLD\nROW AS OLD NEW ROW AS NEW.\n\n•   The standard allows transition tables to be used with column-specific UPDATE triggers,\nbut then the set of rows that should be visible in the transition tables depends on the\ntrigger's column list. This is not currently implemented by PostgreSQL.\n\n•   PostgreSQL only allows the execution of a user-defined function for the triggered action.\nThe standard allows the execution of a number of other SQL commands, such as CREATE\nTABLE, as the triggered action. This limitation is not hard to work around by creating a\nuser-defined function that executes the desired commands.\n\nSQL specifies that multiple triggers should be fired in time-of-creation order.  PostgreSQL\nuses name order, which was judged to be more convenient.\n\nSQL specifies that BEFORE DELETE triggers on cascaded deletes fire after the cascaded DELETE\ncompletes. The PostgreSQL behavior is for BEFORE DELETE to always fire before the delete\naction, even a cascading one. This is considered more consistent. There is also nonstandard\nbehavior if BEFORE triggers modify rows or prevent updates during an update that is caused by\na referential action. This can lead to constraint violations or stored data that does not\nhonor the referential constraint.\n\nThe ability to specify multiple actions for a single trigger using OR is a PostgreSQL\nextension of the SQL standard.\n\nThe ability to fire triggers for TRUNCATE is a PostgreSQL extension of the SQL standard, as\nis the ability to define statement-level triggers on views.\n\nCREATE CONSTRAINT TRIGGER is a PostgreSQL extension of the SQL standard. So is the OR REPLACE\noption.\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "ALTER TRIGGER (ALTERTRIGGER(7)), DROP TRIGGER (DROPTRIGGER(7)), CREATE FUNCTION\n(CREATEFUNCTION(7)), SET CONSTRAINTS (SETCONSTRAINTS(7))\n\n\n\nPostgreSQL 14.23                                2026                               CREATE TRIGGER(7)",
            "subsections": []
        }
    },
    "summary": "CREATETRIGGER - define a new trigger",
    "flags": [],
    "examples": [
        "Execute the function checkaccountupdate whenever a row of the table accounts is about to be",
        "updated:",
        "CREATE TRIGGER checkupdate",
        "BEFORE UPDATE ON accounts",
        "FOR EACH ROW",
        "EXECUTE FUNCTION checkaccountupdate();",
        "Modify that trigger definition to only execute the function if column balance is specified as",
        "a target in the UPDATE command:",
        "CREATE OR REPLACE TRIGGER checkupdate",
        "BEFORE UPDATE OF balance ON accounts",
        "FOR EACH ROW",
        "EXECUTE FUNCTION checkaccountupdate();",
        "This form only executes the function if column balance has in fact changed value:",
        "CREATE TRIGGER checkupdate",
        "BEFORE UPDATE ON accounts",
        "FOR EACH ROW",
        "WHEN (OLD.balance IS DISTINCT FROM NEW.balance)",
        "EXECUTE FUNCTION checkaccountupdate();",
        "Call a function to log updates of accounts, but only if something changed:",
        "CREATE TRIGGER logupdate",
        "AFTER UPDATE ON accounts",
        "FOR EACH ROW",
        "WHEN (OLD.* IS DISTINCT FROM NEW.*)",
        "EXECUTE FUNCTION logaccountupdate();",
        "Execute the function viewinsertrow for each row to insert rows into the tables underlying a",
        "view:",
        "CREATE TRIGGER viewinsert",
        "INSTEAD OF INSERT ON myview",
        "FOR EACH ROW",
        "EXECUTE FUNCTION viewinsertrow();",
        "Execute the function checktransferbalancestozero for each statement to confirm that the",
        "transfer rows offset to a net of zero:",
        "CREATE TRIGGER transferinsert",
        "AFTER INSERT ON transfer",
        "REFERENCING NEW TABLE AS inserted",
        "FOR EACH STATEMENT",
        "EXECUTE FUNCTION checktransferbalancestozero();",
        "Execute the function checkmatchingpairs for each row to confirm that changes are made to",
        "matching pairs at the same time (by the same statement):",
        "CREATE TRIGGER paireditemsupdate",
        "AFTER UPDATE ON paireditems",
        "REFERENCING NEW TABLE AS newtab OLD TABLE AS oldtab",
        "FOR EACH ROW",
        "EXECUTE FUNCTION checkmatchingpairs();",
        "Section 39.4 contains a complete example of a trigger function written in C."
    ],
    "see_also": [
        {
            "name": "ALTERTRIGGER",
            "section": "7",
            "url": "https://www.chedong.com/phpMan.php/man/ALTERTRIGGER/7/json"
        },
        {
            "name": "DROPTRIGGER",
            "section": "7",
            "url": "https://www.chedong.com/phpMan.php/man/DROPTRIGGER/7/json"
        },
        {
            "name": "CREATEFUNCTION",
            "section": "7",
            "url": "https://www.chedong.com/phpMan.php/man/CREATEFUNCTION/7/json"
        },
        {
            "name": "SETCONSTRAINTS",
            "section": "7",
            "url": "https://www.chedong.com/phpMan.php/man/SETCONSTRAINTS/7/json"
        },
        {
            "name": "TRIGGER",
            "section": "7",
            "url": "https://www.chedong.com/phpMan.php/man/TRIGGER/7/json"
        }
    ]
}