Re: what are rules for?

From: "Adam Rich" <adam(dot)r(at)sbcglobal(dot)net>
To: "'Michael Shulman'" <shulman(at)mathcamp(dot)org>, "'Tom Lane'" <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Cc: <pgsql-general(at)postgresql(dot)org>
Subject: Re: what are rules for?
Date: 2008-06-24 04:54:19
Message-ID: 042601c8d5b6$5d475820$17d60860$@r@sbcglobal.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

>
> Can you describe, or point me to somewhere which describes, all the
> things you can do with a rule that you can't do with a trigger? The
> only examples of rules in the manual are (1) logging, which I've just
> been told is much better done with a trigger, and (2) making update,
> insert, and delete work for a view, which is the only way to do it
> because views are not allowed to have update, insert, or delete
> triggers. However, as I have learned in several recent threads, this
> use of rules is fraught with difficulties, especially when the view
> has more than one table, and it seems that it would be much easier if
> triggers were just allowed on views. What is the real purpose of the
> rule system?
>

You can read more about rules here:

http://www.postgresql.org/docs/8.3/interactive/rules.html

The documentation calls rules a "query rewrite" system, which helped
me understand their use. Whereas triggers are called once per row
modified, rules can modify or replace the actual query tree being
executed. There are some fine examples here:

http://www.postgresql.org/docs/8.3/interactive/rules-triggers.html

Rules can be used to change a SELECT statement in-flight. This is
actually how views are implemented in postgresql.

One interesting example is having rules and triggers watching for
deletes or updates on a table. If many rows are modified, rules
can be faster. Take this statement:

DELETE FROM mydata WHERE idval BETWEEN 10000 and 20000;

Say this statement deletes 10,000 rows. The delete trigger would
get called 10,000 times whereas the rule is essentially executed
once, since it can share the WHERE clause of the user's query.

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Craig Ringer 2008-06-24 05:36:17 Re: Method to detect certain characters in column?
Previous Message Ian Meyer 2008-06-24 04:48:38 Re: Method to detect certain characters in column?