41.7. Rules Versus Triggers (2024)

Many things that can be done using triggers can also be implemented using the PostgreSQL rule system. One of the things that cannot be implemented by rules are some kinds of constraints, especially foreign keys. It is possible to place a qualified rule that rewrites a command to NOTHING if the value of a column does not appear in another table. But then the data is silently thrown away and that's not a good idea. If checks for valid values are required, and in the case of an invalid value an error message should be generated, it must be done by a trigger.

In this chapter, we focused on using rules to update views. All of the update rule examples in this chapter can also be implemented using INSTEAD OF triggers on the views. Writing such triggers is often easier than writing rules, particularly if complex logic is required to perform the update.

For the things that can be implemented by both, which is best depends on the usage of the database. A trigger is fired once for each affected row. A rule modifies the query or generates an additional query. So if many rows are affected in one statement, a rule issuing one extra command is likely to be faster than a trigger that is called for every single row and must re-determine what to do many times. However, the trigger approach is conceptually far simpler than the rule approach, and is easier for novices to get right.

Here we show an example of how the choice of rules versus triggers plays out in one situation. There are two tables:

CREATE TABLE computer ( hostname text, -- indexed manufacturer text -- indexed);CREATE TABLE software ( software text, -- indexed hostname text -- indexed);

Both tables have many thousands of rows and the indexes on hostname are unique. The rule or trigger should implement a constraint that deletes rows from software that reference a deleted computer. The trigger would use this command:

DELETE FROM software WHERE hostname = $1;

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

CREATE RULE computer_del AS ON DELETE TO computer DO DELETE FROM software WHERE hostname = OLD.hostname;

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

DELETE FROM computer WHERE hostname = 'mypc.local.net';

the table computer 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:

DELETE FROM software WHERE computer.hostname = 'mypc.local.net' AND software.hostname = computer.hostname;

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

Nestloop -> Index Scan using comp_hostidx on computer -> Index Scan using soft_hostidx on software

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

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

DELETE FROM computer WHERE hostname >= 'old' AND hostname < 'ole'

The command added by the rule will be:

DELETE FROM software WHERE computer.hostname >= 'old' AND computer.hostname < 'ole' AND software.hostname = computer.hostname;

with the plan

Hash Join -> Seq Scan on software -> Hash -> Index Scan using comp_hostidx on computer

The other possible command is:

DELETE FROM computer WHERE hostname ~ '^old';

which results in the following executing plan for the command added by the rule:

Nestloop -> Index Scan using comp_hostidx on computer -> Index Scan using soft_hostidx on software

This shows, that the planner does not realize that the qualification for hostname in computer could also be used for an index scan on software when there are multiple qualification expressions combined with AND, which is what it does in the regular-expression version of the command. The trigger will get invoked once for each of the 2000 old computers that have to be deleted, and that will result in one index scan over computer and 2000 index scans over software. The rule implementation will do it with two commands that use indexes. And it depends on the overall size of the table software whether the rule will still be faster in the sequential scan situation. 2000 command executions from the trigger over the SPI manager take some time, even if all the index blocks will soon be in the cache.

The last command we look at is:

DELETE FROM computer WHERE manufacturer = 'bim';

Again this could result in many rows to be deleted from computer. So the trigger will again run many commands through the executor. The command generated by the rule will be:

DELETE FROM software WHERE computer.manufacturer = 'bim' AND software.hostname = computer.hostname;

The plan for that command will again be the nested loop over two index scans, only using a different index on computer:

Nestloop -> Index Scan using comp_manufidx on computer -> Index Scan using soft_hostidx on software

In any of these cases, the extra commands from the rule system will be more or less independent from the number of affected rows in a command.

The summary is, rules will only be significantly slower than triggers if their actions result in large and badly qualified joins, a situation where the planner fails.

41.7. Rules Versus Triggers (2024)

FAQs

What is the difference between a rule and a trigger? ›

A trigger is fired once for each affected row. A rule modifies the query or generates an additional query. So if many rows are affected in one statement, a rule issuing one extra command is likely to be faster than a trigger that is called for every single row and must re-determine what to do many times.

What is the difference between rules and triggers in Postgres? ›

Rules: Rules are applied during query parsing, meaning they affect the query plan generation. Triggers: Triggers are executed after the completion of an event such as INSERT, UPDATE, or DELETE.

What is instead of triggers in Postgres? ›

In PostgreSQL, INSTEAD OF triggers are a special type of triggers that intercept insert, update, and delete operations on views. It means that when you execute an INSERT , UPDATE , or DELETE statement on a view, PostgreSQL does not directly execute the statement.

What are rules in PostgreSQL? ›

The PostgreSQL rule system allows one to define an alternative action to be performed on insertions, updates, or deletions in database tables. Roughly speaking, a rule causes additional commands to be executed when a given command on a given table is executed.

What is the difference between validation rules and triggers? ›

Validation rules are used to confirm that the data entered into a record meets various data quality/business rules before letting the user save it. Triggers can be used for various different things and can be executed at different times – e.g. when initiating a new record, before saving it, or when a record is deleted.

What classifies as a trigger? ›

Triggers are anything that might cause a person to recall a traumatic experience they've had. For example, graphic images of violence might be a trigger for some people. Less obvious things, including songs, odors, or even colors, can also be triggers, depending on someone's experience.

What are 3 types of SQL triggers? ›

SQL Server offers three different types of triggers, data manipulation language triggers, data definition language triggers, and logon triggers. A user uses these different types of triggers in SQL depending upon their requirements.

When not to use triggers in SQL? ›

Cons of SQL Server Triggers

Triggers needs to be properly documented. Triggers add overhead to DML statements. If there are many nested triggers it could get very hard to debug and troubleshoot, which consumes development time and resources. Recursive triggers are even harder to debug than nested triggers.

Are triggers bad for database? ›

Database triggers have a bad reputation because, like any powerful feature, they can be abused. However, when used appropriately, triggers can be useful for adding additional data logic without changing the application's business logic.

Are triggers still used in SQL? ›

Maintaining database integrity

Triggers can be used to ensure that data in a database remains consistent and accurate. For example, you can define an SQL trigger to make sure a foreign key is copied in a summary table when a new record is inserted.

Do triggers slow down a database? ›

A database with too many triggers can cause events to slow down and generate excess latency to your operations. Designing triggers based on business requirements prevents business logic from creeping into your application code, making your data higher-quality and more consistent.

What happens if a Postgres trigger fails? ›

In all cases, a trigger is executed as part of the same transaction as the statement that triggered it, so if either the statement or the trigger causes an error, the effects of both will be rolled back.

What is the difference between a rule and a trigger in PostgreSQL? ›

A trigger is fired for any row affected once. A rule manipulates the parsetree or generates an additional one. So if many rows are affected in one statement, a rule issuing one extra query would usually do a better job than a trigger that is called for any single row and must execute his operations this many times.

What are the limitations of PostgreSQL? ›

One of the main limitations of PostgreSQL is its lack of support for horizontal scaling. This means that as the workload on a PostgreSQL database increases, it becomes increasingly difficult to distribute the load across multiple machines to improve performance.

How do I drop a rule in PostgreSQL? ›

  1. DROP RULE. DROP RULE — remove a rewrite rule.
  2. Synopsis. DROP RULE [ IF EXISTS ] name ON table_name [ CASCADE | RESTRICT ]
  3. Description. DROP RULE drops a rewrite rule.
  4. Parameters. IF EXISTS. ...
  5. Examples. To drop the rewrite rule newrule : DROP RULE newrule ON mytable;
  6. Compatibility. ...
  7. See Also.

What are trigger rules? ›

This is a medium-size inflatable cylinder with gentle sensory bumps on its surface. Through movement and massage, it provides a deep and focused muscle stimulation that facilitates the myo-fascial release.

What is the meaning of trigger in law? ›

: a currently unenforceable law that upon the occurrence of an event (such as a court decision) becomes enforceable.

What is a trigger in layman's terms? ›

Someone's triggers are things that can cause them to have an extreme reaction of fear, upset, or anger, especially because they remember a traumatic experience. You need to understand what your triggers are, for example loud noises.

What is the difference between an action and a trigger? ›

An action happens as a result of a trigger; it's a response from a triggered event. Check out these examples to see how actions work.

Top Articles
Day 36: Azure Az-900: Factors affecting your cost in Azure.
Shift4 Payments Revenue 2019-2024 | FOUR
Rubratings Tampa
Camera instructions (NEW)
Craftsman M230 Lawn Mower Oil Change
Pga Scores Cbs
Z-Track Injection | Definition and Patient Education
New Day Usa Blonde Spokeswoman 2022
Luciipurrrr_
[2024] How to watch Sound of Freedom on Hulu
The Weather Channel Facebook
Wordscape 5832
Betonnen afdekplaten (schoorsteenplaten) ter voorkoming van lekkage schoorsteen. - HeBlad
Fear And Hunger 2 Irrational Obelisk
Rhinotimes
Uc Santa Cruz Events
Www Craigslist Com Phx
Aspen Mobile Login Help
Everything you need to know about Costco Travel (and why I love it) - The Points Guy
Missed Connections Inland Empire
Moving Sales Craigslist
Craigslist Pet Phoenix
Finalize Teams Yahoo Fantasy Football
Allybearloves
Bekijk ons gevarieerde aanbod occasions in Oss.
Conan Exiles Sorcery Guide – How To Learn, Cast & Unlock Spells
Lost Pizza Nutrition
Bellin Patient Portal
Jermiyah Pryear
Bolsa Feels Bad For Sancho's Loss.
WRMJ.COM
R Baldurs Gate 3
Log in to your MyChart account
Wheeling Matinee Results
Justin Mckenzie Phillip Bryant
Strange World Showtimes Near Atlas Cinemas Great Lakes Stadium 16
Help with your flower delivery - Don's Florist & Gift Inc.
Western Gold Gateway
3496 W Little League Dr San Bernardino Ca 92407
Überblick zum Barotrauma - Überblick zum Barotrauma - MSD Manual Profi-Ausgabe
Gold Dipping Vat Terraria
How To Upgrade Stamina In Blox Fruits
Kb Home The Overlook At Medio Creek
Amateur Lesbian Spanking
Sapphire Pine Grove
Automatic Vehicle Accident Detection and Messageing System – IJERT
Cvs Minute Clinic Women's Services
Superecchll
How To Connect To Rutgers Wifi
Famous Dave's BBQ Catering, BBQ Catering Packages, Handcrafted Catering, Famous Dave's | Famous Dave's BBQ Restaurant
Laurel Hubbard’s Olympic dream dies under the world’s gaze
Obituary Roger Schaefer Update 2020
Latest Posts
Article information

Author: Melvina Ondricka

Last Updated:

Views: 6126

Rating: 4.8 / 5 (48 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Melvina Ondricka

Birthday: 2000-12-23

Address: Suite 382 139 Shaniqua Locks, Paulaborough, UT 90498

Phone: +636383657021

Job: Dynamic Government Specialist

Hobby: Kite flying, Watching movies, Knitting, Model building, Reading, Wood carving, Paintball

Introduction: My name is Melvina Ondricka, I am a helpful, fancy, friendly, innocent, outstanding, courageous, thoughtful person who loves writing and wants to share my knowledge and understanding with you.