Changes between Initial Version and Version 1 of Trigger8


Ignore:
Timestamp:
08/21/26 08:22:02 (27 hours ago)
Author:
235018
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • Trigger8

    v1 v1  
     1= Automatic update of employee/store statistics after an employee is hired
     2
     3=== Description
     4This trigger automatically creates the necessary employee/store work record when a new employee is added to the system.
     5
     6When an employee is hired, the database can automatically associate the employee with the relevant store and initialize their work statistics.
     7
     8This reduces the need for the application to perform additional database operations after creating an employee.
     9
     10==== Tables involved
     11- Employees
     12- Personal
     13- works_in_store
     14
     15==== Type of trigger
     16- AFTER INSERT
     17
     18Activated on the `Employees` table.
     19
     20==== SQL Code
     21{{{#!sql
     22CREATE OR REPLACE FUNCTION initialize_employee_statistics()
     23RETURNS TRIGGER
     24LANGUAGE plpgsql
     25AS $$
     26BEGIN
     27    /*
     28    * The employee is created first.
     29    * Work statistics can be initialized when
     30    * the employee is assigned to a store. 
     31    * The actual store assignment should be handled
     32    * through works_in_store. */
     33    INSERT INTO worked (
     34        employee_id,
     35        total_working_hours,
     36        total_wage
     37    )
     38    VALUES (
     39        NEW.id,
     40        0,
     41        0
     42    );
     43    RETURN NEW;
     44END;
     45$$;
     46
     47CREATE TRIGGER trg_initialize_employee_statistics
     48AFTER INSERT
     49ON employees
     50FOR EACH ROW
     51EXECUTE FUNCTION initialize_employee_statistics();
     52
     53}}}
     54
     55=== Logic explanation
     56
     57After a new employee is inserted, the trigger:
     58
     59**1.** Identifies the newly created employee using NEW.id.
     60**2.** Creates an initial statistics record for the employee.
     61**3.** Sets the initial working hours to 0.
     62**4.** Sets the initial total wage to 0.
     63**5.** Allows the employee creation operation to complete.
     64
     65The employee's statistics can subsequently be updated through the worked relationship as working hours and wages are recorded.
     66
     67=== Reason for trigger
     68
     69This trigger is useful because:
     70
     71- It automatically initializes employee statistics.
     72- It avoids requiring the application to create a second record manually.
     73- It ensures that every employee has an initial statistics record.
     74- It provides a consistent starting point for tracking working hours and wages.
     75- It centralizes employee initialization logic in the database.