| | 1 | = Automatic setting of the last modified date for orders |
| | 2 | |
| | 3 | === Description |
| | 4 | This trigger automatically updates the last_modified_date attribute whenever an existing order is changed. |
| | 5 | |
| | 6 | The application does not need to manually provide the modification timestamp. The database automatically records the exact time when the order was modified. |
| | 7 | |
| | 8 | ==== Tables involved |
| | 9 | - Order |
| | 10 | |
| | 11 | ==== Type of trigger |
| | 12 | - BEFORE UPDATE |
| | 13 | |
| | 14 | Activated on the `Order` table. |
| | 15 | |
| | 16 | ==== SQL Code |
| | 17 | {{{#!sql |
| | 18 | CREATE OR REPLACE FUNCTION update_order_modified_date() |
| | 19 | RETURNS TRIGGER |
| | 20 | LANGUAGE plpgsql |
| | 21 | AS $$ |
| | 22 | BEGIN |
| | 23 | NEW.last_modified_date := CURRENT_TIMESTAMP; |
| | 24 | RETURN NEW; |
| | 25 | END; |
| | 26 | $$; |
| | 27 | |
| | 28 | CREATE TRIGGER trg_update_order_modified_date |
| | 29 | BEFORE UPDATE |
| | 30 | ON "order" |
| | 31 | FOR EACH ROW |
| | 32 | EXECUTE FUNCTION update_order_modified_date(); |
| | 33 | |
| | 34 | }}} |
| | 35 | |
| | 36 | === Logic explanation |
| | 37 | |
| | 38 | Whenever an order is updated, the trigger: |
| | 39 | |
| | 40 | **1.** Detects the update operation. |
| | 41 | **2.** Gets the current timestamp using CURRENT_TIMESTAMP. |
| | 42 | **3.** Stores the timestamp in NEW.last_modified_date. |
| | 43 | **4.** Allows the updated order to be saved. |
| | 44 | |
| | 45 | === Reason for trigger |
| | 46 | |
| | 47 | This trigger is useful because: |
| | 48 | |
| | 49 | - t automatically tracks order modifications. |
| | 50 | - It prevents incorrect or missing modification timestamps. |
| | 51 | - It removes the responsibility from the application layer. |
| | 52 | - It provides a reliable history of when an order was last changed. |