🧠 Second Brain

Search

Search IconIcon to open search

Database Triggers

Last updated May 29, 2024

Triggers are used to ingest data into our data platform or Data Warehouse.

# Pros

  1. Optimization: Triggers operate close to the data, leveraging database optimizations by vendors or the open-source community. This allows for writing efficient triggers tailored to the database system’s specific capabilities.
  2. Data Integrity: A key advantage is maintaining data integrity. We won’t lose deletes or updates. Implementing this through triggers ensures consistency across all applications that manipulate the data instead of scattering the logic across various application codebases.

# Cons

  1. Complexity in Handling Row Counts: Triggers must always check the @@ROWCOUNT variable as the first implementation statement. This is crucial because triggers can fire even when no update or insert exists (e.g., where 1=2 conditions).
  2. Nested Trigger Issues: When triggers cause other triggers to fire, managing row counts becomes complex. It’s often suggested to turn row counting off in such cases.
  3. Delete Operations in Merge Statements: Special attention is needed when dealing with delete operations in merge statements. The @@ROWCOUNT in merge operations represents the total number of rows affected, not the count for individual insert, update, or delete actions within the trigger.
  4. Error Handling: Implementing robust error handling within triggers, such as using TRY-CATCH blocks, is essential to prevent triggers from blocking inserts or causing unintended side effects. This requires careful construction of queries and validation of data.
  5. Performance: If you mass insert/update to a table, it takes substantially longer to insert as each row insert will fire the trigger and its stored procedure.

In essence, while triggers offer advantages in terms of optimization and data integrity, they also come with their complexities, especially regarding row count management, nested trigger interactions, handling exceptional cases like merge statements, and ensuring robust error handling.

Source Links

  1. For the advantages and general information about writing triggers:
  2. For the disadvantages and specific implementation concerns:

Other solutions are Change Data Capture or reading date timestamps like updated_date, or created_data.

Check more on JournalGen, Performance Test Trigger, Trigger Security.


Origin:
References: Change Data Capture (CDC)
Created 2016, Updated: 2023-11-13