Database trigger

A database trigger is procedural code that is automatically executed in response to certain events on a particular table or view in a database. The trigger is mostly used for maintaining the integrity of the information on the database. For example, when a new record (representing a new worker) is added to the employees table, new records should also be created in the tables of the taxes, vacations and salaries. Triggers can also be used to log historical data, for example to keep track of employees' previous salaries.

Triggers in DBMS

Below follows a series of descriptions of how some popular DBMS support triggers.

Oracle

In addition to triggers that fire (and execute PL/SQL code) when data is modified, Oracle 10g supports triggers that fire when schema-level objects (that is, tables) are modified and when user logon or logoff events occur.

Schema-level triggers

  • After Creation
  • Before Alter
  • After Alter
  • Before Drop
  • After Drop
  • Before Insert

The four main types of triggers are:

  1. Row-level trigger: This gets executed before or after any column value of a row changes.
  2. Column-level trigger: This gets executed before or after the specified column changes.
  3. For each row type: This trigger gets executed once for each row of the result set affected by an insert/update/delete.
  4. For each statement type: This trigger gets executed only once for the entire result set, but also fires each time the statement is executed.

System-level triggers

From Oracle 8i, database events - logons, logoffs, startups - can fire Oracle triggers.[1]

Microsoft SQL Server

A list of all available firing events in Microsoft SQL Server for DDL triggers is available on Microsoft Docs.[2]

Performing conditional actions in triggers (or testing data following modification) is done through accessing the temporary Inserted and Deleted tables.

PostgreSQL

Introduced support for triggers in 1997. The following functionality in SQL:2003 was previously not implemented in PostgreSQL:

  • SQL allows triggers to fire on updates to specific columns; As of version 9.0 of PostgreSQL this feature is also implemented in PostgreSQL.
  • The standard allows the execution of a number of SQL statements other than SELECT, INSERT, UPDATE, such as CREATE TABLE as the triggered action. This can be done through creating a stored procedure or function to call CREATE TABLE.[3]

Synopsis:

CREATE TRIGGER name { BEFORE | AFTER } { event [ OR ... ] }
    ON TABLE [ FOR [ EACH ] { ROW | STATEMENT } ]
    EXECUTE PROCEDURE funcname ( arguments )

Firebird

Firebird supports multiple row-level, BEFORE or AFTER, INSERT, UPDATE, DELETE (or any combination of thereof) triggers per table, where they are always "in addition to" the default table changes, and the order of the triggers relative to each other can be specified where it would otherwise be ambiguous (POSITION clause.) Triggers may also exist on views, where they are always "instead of" triggers, replacing the default updatable view logic. (Before version 2.1, triggers on views deemed updatable would run in addition to the default logic.)

Firebird does not raise mutating table exceptions (like Oracle), and triggers will by default both nest and recurse as required (SQL Server allows nesting but not recursion, by default.) Firebird's triggers use NEW and OLD context variables (not Inserted and Deleted tables,) and provide UPDATING, INSERTING, and DELETING flags to indicate the current usage of the trigger.

{CREATE | RECREATE | CREATE OR ALTER} TRIGGER name FOR {table name | view name}
 [ACTIVE | INACTIVE]
 {BEFORE | AFTER}
 {INSERT [OR UPDATE] [OR DELETE] | UPDATE [OR INSERT] [OR DELETE] | DELETE [OR UPDATE] [OR INSERT] }
 [POSITION n] AS
BEGIN
 ....
END

As of version 2.1, Firebird additionally supports the following database-level triggers:

  • CONNECT (exceptions raised here prevent the connection from completing)
  • DISCONNECT
  • TRANSACTION START
  • TRANSACTION COMMIT (exceptions raised here prevent the transaction from committing, or preparing if a two-phase commit is involved)
  • TRANSACTION ROLLBACK

Database-level triggers can help enforce multi-table constraints, or emulate materialized views. If an exception is raised in a TRANSACTION COMMIT trigger, the changes made by the trigger so far are rolled back and the client application is notified, but the transaction remains active as if COMMIT had never been requested; the client application can continue to make changes and re-request COMMIT.

Syntax for database triggers:

{CREATE | RECREATE | CREATE OR ALTER} TRIGGER name
 [ACTIVE | INACTIVE] ON
 {CONNECT | DISCONNECT | TRANSACTION START | TRANSACTION COMMIT | TRANSACTION ROLLBACK}
 [POSITION n] AS
BEGIN
 .....
END

MySQL/MariaDB

Limited support for triggers in the MySQL/MariaDB DBMS was added in the 5.0 version of MySQL, launched in 2005.[4]

As of version 8.0, they allow for DDL (Data Definition Language) triggers and for DML (Data Manipulation Language) triggers. They also allow either type of DDL trigger (AFTER or BEFORE) to be used to define triggers. They are created by using the clause CREATE TRIGGER and deleted by using the clause DROP TRIGGER. The statement called upon an event happens is defined after the clause FOR EACH ROW, followed by a keyword (SET or BEGIN), which indicates whether what follows is an expression or a statement respectively.[5]

IBM DB2 LUW

IBM DB2 for distributed systems known as DB2 for LUW (LUW means Linux, Unix, Windows) supports three trigger types: Before trigger, After trigger and Instead of trigger. Both statement level and row level triggers are supported. If there are more triggers for same operation on table then firing order is determined by trigger creation data. Since version 9.7 IBM DB2 supports autonomous transactions.[6]

Before trigger is for checking data and deciding if operation should be permitted. If exception is thrown from before trigger then operation is aborted and no data are changed. In DB2 before triggers are read only — you can't modify data in before triggers. After triggers are designed for post processing after requested change was performed. After triggers can write data into tables and unlike some[which?] other databases you can write into any table including table on which trigger operates. Instead of triggers are for making views writeable.

Triggers are usually programmed in SQL PL language.

SQLite

CREATE [TEMP | TEMPORARY] TRIGGER [IF NOT EXISTS] [database_name .] trigger_name
[BEFORE | AFTER | INSTEAD OF] {DELETE | INSERT | UPDATE [OF column_name [, column_name]...]} 
ON {table_name | view_name}
   [FOR EACH ROW] [WHEN condition is mandatory ]
BEGIN
   ...
END

SQLite only supports row-level triggers, not statement-level triggers.

Updateable views, which are not supported in SQLite, can be emulated with INSTEAD OF triggers.

XML databases

An example of implementation of triggers in non-relational database can be Sedna, that provides support for triggers based on XQuery. Triggers in Sedna were designed to be analogous to SQL:2003 triggers, but natively base on XML query and update languages (XPath, XQuery and XML update language).

A trigger in Sedna is set on any nodes of an XML document stored in database. When these nodes are updated, the trigger automatically executes XQuery queries and updates specified in its body. For example, the following trigger cancels person node deletion if there are any open auctions referenced by this person:

CREATE TRIGGER "trigger3"
    BEFORE DELETE
    ON doc("auction")/site//person
    FOR EACH NODE
    DO
    {
        if (exists($WHERE//open_auction/bidder/personref/@person=$OLD/@id))
        then ( )
        else $OLD;
    }

Row and statement level triggers

To understand how trigger behavior works, you need to be aware of the two main types of triggers; these are Row and Statement level triggers. The distinction between the two is how many times the code within the trigger is executed, and at what time.

Suppose you have a trigger that is made to be called on an UPDATE to a certain table. Row level triggers would execute once for each row that is affected by the UPDATE. It is important to keep in mind if no rows are affected by the UPDATE command, the trigger will not execute any code within the trigger. Statement level triggers will be called once regardless of how many rows are affected by the UPDATE. Here it is important to note that even if the UPDATE command didn't affect any rows, the code within the trigger will still be executed once.

Using the BEFORE and AFTER options[7] determine when the trigger is called. Suppose you have a trigger that is called on an INSERT to a certain table. If your trigger is using the BEFORE option, the code within the trigger will be executed before the INSERT into the table occurs. A common use of the BEFORE trigger is to verify the input values of the INSERT, or modify the values accordingly. Now let's say we have a trigger that uses AFTER instead. The code within the trigger is executed after the INSERT happens to the table. An example use of this trigger is creating an audit history of who has made inserts into the database, keeping track of the changes made. When using these options you need to keep a few things in mind. The BEFORE option does not allow you to modify tables, that is why input validation is a practical use. Using AFTER triggers allows you to modify tables such as inserting into an audit history table.

When creating a trigger to determine if it is statement or row level simply include the FOR EACH ROW clause for a row level, or omit the clause for a statement level. Be cautious of using additional INSERT/UPDATE/DELETE commands within your trigger, because trigger recursion is possible, causing unwanted behavior. In the examples below each trigger is modifying a different table, by looking at what is being modified you can see some common applications of when different trigger types are used.

The following is an Oracle syntax example of a row level trigger that is called AFTER an update FOR EACH ROW affected. This trigger is called on an update to a phone book database. When the trigger is called it adds an entry into a separate table named phone_book_audit. Also take note of triggers being able to take advantage of schema objects like sequences,[8] in this example audit_id_sequence.nexVal is used to generate unique primary keys in the phone_book_audit table.

CREATE OR REPLACE TRIGGER phone_book_audit
  AFTER UPDATE ON phone_book FOR EACH ROW
BEGIN
  INSERT INTO phone_book_audit 
    (audit_id,audit_change, audit_l_name, audit_f_name, audit_old_phone_number, audit_new_phone_number, audit_date) 
    VALUES
    (audit_id_sequence.nextVal,'Update', :OLD.last_name, :OLD.first_name, :OLD.phone_number, :NEW.phone_number, SYSDATE);
END;

Now calling an UPDATE on the phone_book table for people with the last name 'Jones'.

UPDATE phone_book SET phone_number = '111-111-1111' WHERE last_name = 'Jones';
Audit_ID Audit_Change F_Name L_Name New_Phone_Number Old_Phone_Number Audit_Date
1 Update Jordan Jones 111-111-1111 098-765-4321 02-MAY-14
2 Update Megan Jones 111-111-1111 111-222-3456 02-MAY-14


Notice that the phone_number_audit table is now populated with two entries. This is due to the database having two entries with the last name of 'Jones'. Since the update modified two separate row values, the created trigger was called twice; once after each modification.

After - statement-level trigger

An Oracle syntax statement trigger that is called after an UPDATE to the phone_book table. When the trigger gets called it makes an insert into phone_book_edit_history table

CREATE OR REPLACE TRIGGER phone_book_history
  AFTER UPDATE ON phone_book
BEGIN
  INSERT INTO phone_book_edit_history 
    (audit_history_id, username, modification, edit_date) 
    VALUES
    (audit_history_id_sequence.nextVal, USER,'Update', SYSDATE);
END;

Now doing exactly the same update as the above example, however this time with a statement level trigger.

UPDATE phone_book SET phone_number = '111-111-1111' WHERE last_name = 'Jones';
Audit_History_ID Username Modification Edit_Date
1 HAUSCHBC Update 02-MAY-14

The result shows that the trigger was only called once, even though the update did change two rows.

Before each - row-level trigger

This example demonstrates a BEFORE EACH ROW trigger that modifies the INSERT using a WHEN conditional. If the last name is larger than 10 letters, using the SUBSTR function[9] we change the last_name column value to an abbreviation.

CREATE OR REPLACE TRIGGER phone_book_insert
  BEFORE INSERT ON phone_book FOR EACH ROW
  WHEN (LENGTH(new.last_name) > 10)
BEGIN
    :new.last_name := SUBSTR(:new.last_name,0,1);
END;

Now performing an INSERT of someone with a large name.

INSERT INTO phone_book VALUES
(6, 'VeryVeryLongLastName', 'Erin', 'Minneapolis', 'MN', '989 University Drive', '123-222-4456', 55408, TO_DATE('11/21/1991', 'MM/DD/YYYY'));
Person_ID Last_Name First_Name City State_Abbreviation Address Phone_Number Zip_code DOB
6 V Erin Minneapolis MN 989 University Drive 123-222-4456 55408 21-NOV-91

The trigger worked as per the result above, modifying the value of the INSERT before it was executed.

Before - statement-level trigger

Using a BEFORE statement trigger is particularly useful when enforcing database restrictions.[10] This example demonstrate how to enforce a restriction upon someone named "SOMEUSER" on the table phone_book.

CREATE OR REPLACE TRIGGER hauschbc 
  BEFORE INSERT ON SOMEUSER.phone_book
BEGIN
    RAISE_APPLICATION_ERROR (
         num => -20050,
         msg => 'Error message goes here.');
END;

Now, when "SOMEUSER" is logged in after attempting any INSERT this error message will show:

SQL Error: ORA-20050: Error message goes here.

Custom errors such as this one has a restriction on what the num variable can be defined as. Because of the numerous other pre-defined errors this variable must be in the range of −20000 to −20999.

References

  1. ^ Nanda, Arup; Burleson, Donald K. (2003). "9". In Burleson, Donald K. (ed.). Oracle Privacy Security Auditing: Includes Federal Law Compliance with HIPAA, Sarbanes Oxley and the Gramm Leach Bliley Act GLB. Oracle in-focus series. Vol. 47. Kittrell, North Carolina: Rampant TechPress. p. 511. ISBN 9780972751391. Retrieved 2018-04-17. [...] system-level triggers [...] were introduced in Oracle8i. [...] system-level triggers are fired at specific system events such as logon, logoff, database startup, DDL execution, and servererror [...].
  2. ^ "DDL Events - SQL Server". 15 March 2023.
  3. ^ "PostgreSQL: Documentation: 9.0: CREATE TRIGGER". www.postgresql.org. 8 October 2015.
  4. ^ MySQL 5.0 Reference Manual. "Triggers. MySQL 5.0 added limited support for triggers", Oracle Corporation, Retrieved on 4 March 2020.
  5. ^ "MySQL :: MySQL 8.0 Reference Manual :: 25.3.1 Trigger Syntax and Examples".
  6. ^ "Autonomous transactions". www.ibm.com. July 30, 2009.
  7. ^ "6 Using Triggers". docs.oracle.com.
  8. ^ "Oracle's Documentation on Sequences". Archived from the original on 2011-12-01.
  9. ^ "Oracle SQL Functions – The Complete List". December 26, 2014.
  10. ^ "Database PL/SQL Language Reference". docs.oracle.com.

External links

Read other articles:

Chemical compound Baricitinib Clinical dataTrade namesOlumiant, othersOther namesINCB28050, LY3009104AHFS/Drugs.comMonographMedlinePlusa618033License data US DailyMed: Baricitinib Pregnancycategory AU: D[1][2] Use is contraindicated Routes ofadministrationBy mouthATC codeL04AF02 (WHO) Legal statusLegal status AU: S4 (Prescription only)[4][1] CA: ℞-only[5][6] US: WARNING[3]Rx-only[7] EU:…

Japanese manga series and franchise This article is about the manga series. For the Spanish-language court show, see Caso Cerrado. For other uses, see Case Closed (disambiguation). Case Closed36th North American volume cover, featuring Conan Edogawa名探偵コナン(Meitantei Konan)GenreMystery[1]Thriller[1] MangaWritten byGosho AoyamaPublished byShogakukanEnglish publisherNA: Viz MediaSEA: Shogakukan Asia (as Detective Conan)ImprintShōnen Sunday ComicsMagazineWeekly …

La procédure d'essai mondiale harmonisée pour les véhicules légers (en anglais Worldwide harmonized Light vehicles Test Procedures, ou WLTP) est une norme d'essais d'homologation des véhicules qui permet de mesurer la consommation de carburant, l'autonomie électrique et les rejets de CO2 et de polluants. Cette procédure d'essai concerne les voitures particulières et les véhicules utilitaires légers. D'autres procédures concernent les motos et les véhicules lourds. La WLTP a été mis…

National flag JordanUseCivil and state flag, civil and state ensign Proportion1:2Adopted16 April 1928; 96 years ago (1928-04-16)DesignA horizontal triband of black, white and green; with a red chevron based on the hoist side containing a white seven-pointed star UseRoyal standard of the KingDesignPan-Arab colors resembles the Rising Sun Flag; Jordanian flag in the center, with the star being replaced with a crown UseRoyal standard of the Crown Prince UseThe Hashemite Standard, …

Burmese army general Lieutenant GeneralKyaw Swar Linကျော်စွာလင်းQuartermaster General of Myanmar ArmyIncumbentAssumed office May 2020Preceded byLieutenant General Nyo Saw Personal detailsBorn1971 (age 52–53)NationalityBurmeseSpouseNan Ku KuAlma materDefence Services AcademyMilitary serviceAllegiance MyanmarBranch/service Myanmar ArmyRank Lieutenant General Kyaw Swar Lin (Burmese: ကျော်စွာလင်း) is a Burmese military general …

Canadian actor and writer Cas AnvarAnvar in 2019Born (1966-03-15) 15 March 1966 (age 58)Regina, Saskatchewan, CanadaAlma materNational Theatre SchoolOccupation(s)Actor, writerYears active1988–presentKnown for Dr Singh in The Tournament Alex Kamal in The Expanse Websitewww.casanvar.com Cas Anvar (Persian: کاس انور; born 15 March 1966)[1][2][3] is a Canadian actor known for his role in the SyFy/Amazon Prime Video science fiction television serie…

Peringkat kredit adalah penilaian dari risiko kredit dari seorang individu, perusahaan, ataupun suatu negara. Peringkat kredit dibuat berdasarkan riwayat finansial dan aset yang dimiliki sekarang serta kewajiban. Pada umumnya peringkat kredit suatu negara mencerminkan kelayakan kredit sebuah negara yaitu kemampuan negara membayar kembali utang-utangnya sehingga tidak akan menimbulkan risiko gagal bayar kepada kreditur atau investor dengan kemungkinan kalah melaksanakan pengembalian / pembayaran …

Anatoly KulikovАнатолий КуликовKulikov in 2018Minister of Internal AffairsIn office6 July 1995 – 23 March 1998PresidentBoris YeltsinPrime MinisterViktor ChernomyrdinPreceded byViktor YerinSucceeded bySergei Stepashin Personal detailsBorn (1946-09-04) September 4, 1946 (age 77)Aigursky, Stavropol Krai, RSFSR, USSRMilitary serviceAllegiance Soviet Union RussiaBranch/serviceSoviet Internal TroopsRussian Internal troopsYears of service1966-1998RankGenera…

This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Communist Party of Malta – news · newspapers · books · scholar · JSTOR (January 2023) (Learn how and when to remove this message) Political party in Malta Communist Party of Malta Partit Komunista MaltiAbbreviationPKMGeneral SecretaryVictor DegiovanniFounderAn…

Fort in Jalore, Rajasthan, India This article includes a list of general references, but it lacks sufficient corresponding inline citations. Please help to improve this article by introducing more precise citations. (February 2020) (Learn how and when to remove this message) Jalore FortJalore Quilla or Swanagiri DurgPart of Marwar RajputanaJalore district, Rajasthan Temples at Jalore FortJalore FortCoordinates25°20′14″N 72°36′52″E / 25.3373°N 72.6144°E / 25.33…

2023 Supercoppa ItalianaTournament detailsHost country Saudi ArabiaCityRiyadhDates18–22 January 2024Teams4Final positionsChampionsInternazionale (8th title)Runners-upNapoliTournament statisticsMatches played3Goals scored7 (2.33 per match)Attendance55,429 (18,476 per match)Top scorer(s)Alessio Zerbin(2 goals)← 2022 2024 → International football competition The 2023 Supercoppa Italiana (branded as the EA Sports FC Supercup for sponsorship reasons) was the 36th edi…

حومة السوق   الإحداثيات 33°52′00″N 10°51′00″E / 33.866666666667°N 10.85°E / 33.866666666667; 10.85   تقسيم إداري  البلد تونس[1]  التقسيم الأعلى ولاية مدنين  عدد السكان  عدد السكان 75904   معلومات أخرى 4170  رمز جيونيمز 2470384  الموقع الرسمي الموقع الرسمي  تعديل مصدري - …

Geographic region in the Appalachian Mountains of the Eastern United States This article is about the region in the United States. For other uses, see Appalachia (disambiguation). Region in United States of AmericaAppalachiaRegionLeft–right from top: Pittsburgh skyline New River Gorge Bridge campus of Appalachian State University Smoky Mountains Roanoke skyline mountains of North Georgia view from the Appalachian Trail Red and dark red counties form the Appalachian Regional Commission; dark re…

2014 Japanese animated film directed by Tsuneo Kobayashi The Last: Naruto the MovieJapanese film posterDirected byTsuneo KobayashiScreenplay byMaruo KyozukaStory byMasashi KishimotoMaruo KyozukaBased onNarutoby Masashi KishimotoProduced by Takuyuki Hirobe Naoji Hohnokidani Shoji Matsui Starring Junko Takeuchi Nana Mizuki Chie Nakamura Showtaro Morikubo Satoshi Hino Kazuhiko Inoue Noriaki Sugiyama CinematographyAtsuho MatsumotoEdited bySeiji MoritaMusic by Yasuharu Takanashi Yaiba Productioncompa…

NGC 6872 e IC 4970Galassie interagentiNGC 6872 e IC 4970ScopertaScopritoreJohn Herschel Data1835 Dati osservativi(epoca J2000)CostellazionePavone Ascensione retta20h 16m 56,5s/20h 16m 57,1s[1] Declinazione-70° 46′ 06″/-70° 44′ 58″[1] Distanza220[2] milioni di a.l.   Magnitudine apparente (V)12.7 / 14.7[1] Dimensione apparente (V)6′.0 × 1′.7 / 0′.7 × 0′.2[…

Dewan Perwakilan Rakyat Daerah Kabupaten Buton SelatanDewan Perwakilan RakyatKabupaten Buton Selatan2019-2024JenisJenisUnikameral Jangka waktu5 tahunSejarahSesi baru dimulai1 Oktober 2019PimpinanKetuaLa Ode Armada (PDI-P) sejak 25 Oktober 2019 Wakil Ketua IAliadi, S.Pd. (Hanura) sejak 25 Oktober 2019 Wakil Ketua IIPomili Womal, S.Pd.SD. (Demokrat) sejak 25 Oktober 2019 KomposisiAnggota20Partai & kursi  PDI-P (5)   NasDem (1)   PKB (1)   Han…

Like I Wouldsingolo discograficoScreenshot tratto dal video del branoArtistaZayn Pubblicazione11 marzo 2016 Durata3:23 Album di provenienzaMind of Mine GenereElettropop EtichettaRCA Registrazione2015 FormatiDownload digitale, streaming CertificazioniDischi d'argento Regno Unito[1](vendite: 200 000+) Dischi d'oro Australia[2](vendite: 35 000+) Italia[3](vendite: 25 000+) Svezia[4](vendite: 20 000+) Dischi di…

Set index for Scott baronets There have been twelve baronetcies created for people with the surname Scott, one in the Baronetage of England, two in the Baronetage of Nova Scotia, and nine in the Baronetage of the United Kingdom. Sir Walter Scott, 1st Baronet of Abbotsford Scott baronets of Kew Green (1653) Scott baronets, of Thirlestane (1666): see the Lord Napier Scott baronets of Ancrum (1671) Scott baronets of Great Barr 1806 Sibbald, later Scott baronets, of Dunninald (1806): see Sibbald bar…

Pola drum blast beat Playⓘ. Listen to Example 1 Listen to Example 2 Listen to Example 3 Listen to Example 4 Bermasalah memainkan berkas-berkas ini? Lihat bantuan media. Blast Beat adalah sebuah beat drum yang asalnya berasal dari jazz, dan biasanya blast beat ini diasosiasikan dengan musik metal. Derek Roddy di bukunya yang berjudul The Evolution Of Blast Beats ini mendefinisikan Blast Beat sebagai rudiment single stroke yang dimainkan secara bergantian antara tangan dan kaki, dimana tangan di…

British politician The Right HonourableThe Viscount AllendaleDL JP PCCaptain of the Yeomen of the GuardIn office29 April 1907 – 2 October 1911MonarchsEdward VII George VPrime MinisterSir Henry Campbell-Bannerman H. H. AsquithPreceded byThe Earl WaldegraveSucceeded byThe Earl of Craven Personal detailsBorn2 December 1860Bywell Hall, NorthumberlandDied12 December 1923London, EnglandNationalityBritishPolitical partyLiberalSpouseLady Alexandrina Louisa Maud Vane-TempestAlma materTrinity C…