Skip to content

Database Trigger Analysis (dtrigger.sql)

This script provides comprehensive analysis of database triggers, displaying detailed information about trigger definitions, firing conditions, status, and implementation code. It’s essential for trigger management, debugging, security auditing, and understanding database business logic implementation. The script shows trigger types, events, status, conditional clauses, and the complete trigger body code.

rem dtrigger.sql
rem
set long 4000
rem
ttitle 'Database Triggers'
rem
col owner format a8 heading 'OWNER'
col table_owner format a8 heading 'TABLE|OWNER'
col table_name format a30 heading 'TABLE NAME'
col trigger_name format a30 heading 'TRIGGER NAME'
col trigger_type format a16 heading 'TRIGGER TYPE'
col triggering_event format a26 heading 'TRIGGERING EVENT'
col stataus format a1 heading 'S'
col when_clause format a80 heading 'WHEN CLAUSE'
col description format a80 heading 'DESCRIPTION'
col trigger_body format a80 heading 'TRIGGER BODY'
rem
select table_owner, table_name, trigger_name,
trigger_type, triggering_event,
decode( status, 'ENABLED', null, 'DISABLED', 'X', '?' ) status,
when_clause, description, trigger_body
from sys.dba_triggers
where table_owner like upper('&owner')
and table_name like upper('&table')
and trigger_name like upper('&trigger')
order by table_owner, table_name, trigger_name;
rem
set long 80
  • Comprehensive Trigger Information: Shows type, events, conditions, and code
  • Multiple Filtering Options: Filter by owner, table, and trigger name
  • Status Indication: Visual indicators for enabled/disabled triggers
  • Complete Code Display: Shows full trigger body with extended LONG setting
  • Conditional Logic: Displays WHEN clauses for conditional triggers
  • Organized Output: Sorted by owner, table, and trigger name
  • Debugging Support: Essential for trigger troubleshooting and analysis
@dtrigger.sql

Input Parameters:

  • owner: Schema owner name or pattern (press Enter for all)
  • table: Table name or pattern (press Enter for all)
  • trigger: Trigger name or pattern (press Enter for all)
SELECT on SYS.DBA_TRIGGERS
Database Triggers
TABLE TABLE NAME TRIGGER NAME TRIGGER TYPE TRIGGERING EVENT S WHEN CLAUSE
OWNER DESCRIPTION
TRIGGER BODY
-------- ------------------------------ ------------------------------ ---------------- ------------------------- - ------------
HR EMPLOYEES EMPLOYEES_AUDIT_TRG AFTER EACH ROW INSERT OR UPDATE OR DELETE
Employee audit trigger
BEGIN
INSERT INTO emp_audit_log
VALUES (:NEW.employee_id, USER, SYSDATE, :NEW.salary);
END;
SALES ORDERS ORDER_STATUS_TRG BEFORE EACH ROW UPDATE
Order status validation
BEGIN
IF :NEW.status NOT IN ('PENDING','APPROVED','SHIPPED')
THEN
RAISE_APPLICATION_ERROR(-20001,'Invalid status');
END IF;
END;
FINANCE TRANSACTIONS TXN_AMOUNT_CHECK BEFORE EACH ROW INSERT OR UPDATE amount > 10000
Large transaction validation
BEGIN
INSERT INTO large_txn_log
VALUES (:NEW.txn_id, :NEW.amount, SYSDATE);
END;
SALES PRODUCTS PRODUCT_PRICE_HISTORY AFTER EACH ROW UPDATE X price column updated
Track price changes (DISABLED)
BEGIN
IF :OLD.price != :NEW.price THEN
INSERT INTO price_history VALUES(...);
END IF;
END;
  • TABLE OWNER: Schema owner of the table
  • TABLE NAME: Name of the table the trigger is defined on
  • TRIGGER NAME: Name of the trigger
  • TRIGGER TYPE: Timing and level (BEFORE/AFTER, ROW/STATEMENT)
  • TRIGGERING EVENT: Events that fire the trigger (INSERT, UPDATE, DELETE)
  • S: Status indicator (blank=ENABLED, X=DISABLED, ?=other)
  • WHEN CLAUSE: Conditional clause for trigger firing
  • DESCRIPTION: Trigger description/comments
  • TRIGGER BODY: Complete PL/SQL code of the trigger
-- BEFORE trigger characteristics:
-- Fire before the triggering event
-- Can modify NEW values
-- Used for validation and value modification
-- Can prevent the operation (raise exception)
-- AFTER trigger characteristics:
-- Fire after the triggering event
-- Cannot modify NEW values
-- Used for auditing and logging
-- Ideal for cascade operations
-- INSTEAD OF trigger characteristics:
-- Used on views, not tables
-- Replace the triggering event
-- Enable DML on complex views
-- Define custom DML logic
-- FOR EACH ROW characteristics:
-- Fire once per affected row
-- Access to :OLD and :NEW values
-- Can use WHEN clause
-- Higher overhead for bulk operations
-- Statement-level characteristics:
-- Fire once per SQL statement
-- No access to row-level data
-- Lower overhead for bulk operations
-- Used for statement-level validations
  1. Trigger Management

    • Review trigger definitions and logic
    • Identify disabled or problematic triggers
    • Plan trigger maintenance and updates
    • Document trigger functionality
  2. Security Auditing

    • Review security-related triggers
    • Validate audit trail implementations
    • Identify unauthorized trigger modifications
    • Assess data protection mechanisms
  3. Performance Analysis

    • Identify performance-impacting triggers
    • Analyze trigger complexity and overhead
    • Plan trigger optimization
    • Assess DML performance impact
  4. Business Logic Review

    • Understand implemented business rules
    • Validate data integrity enforcement
    • Review calculation and derivation logic
    • Plan application logic migration
-- Disabled triggers (X status) indicate:
-- Intentionally disabled for maintenance
-- Performance issues being investigated
-- Broken trigger logic
-- Temporary workarounds
-- Enable/disable triggers:
ALTER TRIGGER trigger_name ENABLE;
ALTER TRIGGER trigger_name DISABLE;
-- Disable all table triggers:
ALTER TABLE table_name DISABLE ALL TRIGGERS;
-- Performance considerations:
-- Row-level triggers on high-volume tables
-- Complex trigger logic
-- Multiple triggers on same event
-- Cascading trigger effects
-- Trigger optimization:
-- Minimize trigger complexity
-- Use WHEN clauses to reduce firing
-- Consider statement-level triggers
-- Optimize embedded SQL
-- Analyze specific schema:
Enter value for owner: HR
Enter value for table: %
Enter value for trigger: %
-- Review triggers on specific table:
Enter value for owner: %
Enter value for table: EMPLOYEES
Enter value for trigger: %
-- Find triggers by name pattern:
Enter value for owner: %
Enter value for table: %
Enter value for trigger: %AUDIT%
-- Review all triggers:
Enter value for owner: %
Enter value for table: %
Enter value for trigger: %
-- Common audit trigger patterns:
-- Log all changes to audit tables
-- Capture user and timestamp information
-- Record old and new values
-- Support compliance requirements
-- Security audit triggers:
-- Monitor sensitive data access
-- Log privilege escalations
-- Track unauthorized modifications
-- Support forensic analysis
-- Validation trigger patterns:
-- Complex business rule validation
-- Cross-table consistency checks
-- Data format and range validation
-- Referential integrity enforcement
-- Data quality triggers:
-- Automatic data cleansing
-- Format standardization
-- Duplicate detection
-- Completeness validation
-- Calculation trigger patterns:
-- Automatic field calculations
-- Summary and aggregate updates
-- Denormalization maintenance
-- Cache refresh operations
-- ORA-04091: table is mutating
-- Caused by: Row-level trigger queries same table
-- Solutions: Use statement-level triggers
-- Implement with autonomous transactions
-- Redesign trigger logic
-- Performance problems:
-- Triggers causing slowdowns
-- Excessive trigger complexity
-- Cascading trigger chains
-- Solutions: Optimize trigger code
-- Use WHEN clauses
-- Consider alternatives
-- Trigger logic issues:
-- Incorrect business rule implementation
-- Missing error handling
-- Infinite loop conditions
-- Solutions: Code review and testing
-- Add proper exception handling
-- Implement safeguards
-- Test trigger behavior:
-- Create test scenarios
-- Use DBMS_OUTPUT for debugging
-- Log intermediate values
-- Test error conditions
-- Assess trigger impact:
-- Monitor performance metrics
-- Check for side effects
-- Validate business logic
-- Test with realistic data volumes
-- Security assessment:
-- Review trigger privileges
-- Validate definer rights usage
-- Check for privilege escalation
-- Assess data access patterns
-- Code security review:
-- SQL injection vulnerability
-- Improper exception handling
-- Hardcoded credentials
-- Sensitive data exposure
-- Compliance considerations:
-- Audit trail completeness
-- Data retention requirements
-- Privacy protection measures
-- Change tracking accuracy
-- Best practice guidelines:
-- Keep triggers simple and focused
-- Minimize performance impact
-- Handle exceptions properly
-- Document trigger purpose
-- Implementation standards:
-- Consistent naming conventions
-- Standard error handling
-- Proper privilege management
-- Code review processes
-- Monitoring schedule:
-- Monthly trigger status review
-- Quarterly performance assessment
-- Annual security audit
-- Change impact analysis
-- Maintain documentation:
-- Trigger purpose and logic
-- Business rule implementation
-- Performance characteristics
-- Maintenance procedures
-- Version control considerations:
-- Track trigger definition changes
-- Maintain deployment scripts
-- Document change history
-- Support rollback procedures
-- Testing framework:
-- Unit testing for trigger logic
-- Integration testing with applications
-- Performance testing under load
-- Regression testing after changes
-- Deployment procedures:
-- Impact assessment
-- Rollback planning
-- Testing validation
-- Production deployment

This script is essential for:

  1. Trigger Management - Comprehensive analysis of database trigger definitions
  2. Security Auditing - Reviewing trigger-based security implementations
  3. Performance Analysis - Identifying trigger performance impacts
  4. Business Logic Review - Understanding implemented business rules
  5. Debugging Support - Troubleshooting trigger-related issues