CREATE RULE

This page documents the preview version (v2.23). Preview includes features under active development and is for development and testing only. For production, use the stable version (v2024.1). To learn more, see Versioning.

Synopsis

Use the CREATE RULE statement to create a rule.

Syntax

create_rule ::= CREATE [ OR REPLACE ] RULE rule_name AS ON rule_event 
                TO table_name  [ WHERE boolean_expression ] DO 
                [ ALSO | INSTEAD ] { NOTHING
                                     | command
                                     | ( command [ ; ... ] ) }

rule_event ::= SELECT | INSERT | UPDATE | DELETE

command ::= SELECT | INSERT | UPDATE | DELETE | NOTIFY

create_rule

CREATEORREPLACERULErule_nameASONrule_eventTOtable_nameWHEREboolean_expressionDOALSOINSTEADNOTHINGcommand(;command)

rule_event

SELECTINSERTUPDATEDELETE

command

SELECTINSERTUPDATEDELETENOTIFY

Semantics

See the semantics of each option in the [PostgreSQL docs][postgresql-docs-create-rule].

Examples

Basic example.

yugabyte=# CREATE TABLE t1(a int4, b int4);
yugabyte=# CREATE TABLE t2(a int4, b int4);
yugabyte=# CREATE RULE t1_to_t2 AS ON INSERT TO t1 DO INSTEAD
             INSERT INTO t2 VALUES (new.a, new.b);
yugabyte=# INSERT INTO t1 VALUES (3, 4);
yugabyte=# SELECT * FROM t1;
 a | b
---+---
(0 rows)
yugabyte=# SELECT * FROM t2;
 a | b
---+---
 3 | 4
(1 row)

See also