Home Explore Blog CI



postgresql

31th chunk of `doc/src/sgml/rules.sgml`
63c5f29ccd80ebecbbf917b8f60b00634d283498e85610140000000100000975
 <literal>software</literal>
    that reference a deleted computer.  The trigger would use this command:

<programlisting>
DELETE FROM software WHERE hostname = $1;
</programlisting>

    Since the trigger is called for each individual row deleted from
    <literal>computer</literal>, it can prepare and save the plan for this
    command and pass the <structfield>hostname</structfield> value in the
    parameter.  The rule would be written as:

<programlisting>
CREATE RULE computer_del AS ON DELETE TO computer
    DO DELETE FROM software WHERE hostname = OLD.hostname;
</programlisting>
   </para>

   <para>
    Now we look at different types of deletes. In the case of a:

<programlisting>
DELETE FROM computer WHERE hostname = 'mypc.local.net';
</programlisting>

    the table <literal>computer</literal> is scanned by index (fast), and the
    command issued by the trigger would also use an index scan (also fast).
    The extra command from the rule would be:

<programlisting>
DELETE FROM software WHERE computer.hostname = 'mypc.local.net'
                       AND software.hostname = computer.hostname;
</programlisting>

    Since there are appropriate indexes set up, the planner
    will create a plan of

<literallayout class="monospaced">
Nestloop
  -&gt;  Index Scan using comp_hostidx on computer
  -&gt;  Index Scan using soft_hostidx on software
</literallayout>

    So there would be not that much difference in speed between
    the trigger and the rule implementation.
   </para>

   <para>
    With the next delete we want to get rid of all the 2000 computers
    where the <structfield>hostname</structfield> starts with
    <literal>old</literal>. There are two possible commands to do that. One
    is:

<programlisting>
DELETE FROM computer WHERE hostname &gt;= 'old'
                       AND hostname &lt;  'ole'
</programlisting>

    The command added by the rule will be:

<programlisting>
DELETE FROM software WHERE computer.hostname &gt;= 'old' AND computer.hostname &lt; 'ole'
                       AND software.hostname = computer.hostname;
</programlisting>

    with the plan

<literallayout class="monospaced">
Hash Join
  -&gt;  Seq Scan on software
  -&gt;  Hash
    -&gt;  Index Scan using comp_hostidx on computer
</literallayout>

    The other possible command is:

<programlisting>
DELETE FROM computer WHERE hostname ~ '^old';
</programlisting>

    which results

Title: Comparison of Rules and Triggers in PostgreSQL
Summary
This section continues to compare the performance of rules and triggers in PostgreSQL, providing examples of different delete operations and analyzing the query plans generated by the planner, highlighting the differences in speed and efficiency between rule and trigger implementations.