| | 1 | = Automatic update of employee/store statistics after an employee is hired |
| | 2 | |
| | 3 | === Description |
| | 4 | This trigger automatically creates the necessary employee/store work record when a new employee is added to the system. |
| | 5 | |
| | 6 | When an employee is hired, the database can automatically associate the employee with the relevant store and initialize their work statistics. |
| | 7 | |
| | 8 | This 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 | |
| | 18 | Activated on the `Employees` table. |
| | 19 | |
| | 20 | ==== SQL Code |
| | 21 | {{{#!sql |
| | 22 | CREATE OR REPLACE FUNCTION initialize_employee_statistics() |
| | 23 | RETURNS TRIGGER |
| | 24 | LANGUAGE plpgsql |
| | 25 | AS $$ |
| | 26 | BEGIN |
| | 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; |
| | 44 | END; |
| | 45 | $$; |
| | 46 | |
| | 47 | CREATE TRIGGER trg_initialize_employee_statistics |
| | 48 | AFTER INSERT |
| | 49 | ON employees |
| | 50 | FOR EACH ROW |
| | 51 | EXECUTE FUNCTION initialize_employee_statistics(); |
| | 52 | |
| | 53 | }}} |
| | 54 | |
| | 55 | === Logic explanation |
| | 56 | |
| | 57 | After 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 | |
| | 65 | The employee's statistics can subsequently be updated through the worked relationship as working hours and wages are recorded. |
| | 66 | |
| | 67 | === Reason for trigger |
| | 68 | |
| | 69 | This 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. |