Changes between Initial Version and Version 1 of Trigger5


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

--

Legend:

Unmodified
Added
Removed
Modified
  • Trigger5

    v1 v1  
     1= Prevention of deleting stores with existing orders or reports
     2
     3=== Description
     4This trigger prevents a store from being deleted if the store has existing orders or reports associated with it.
     5
     6A store should not be removed while historical business data still references it, because this could result in the loss of important information about sales, reports, and store activity.
     7
     8==== Tables involved
     9- Store
     10- Report
     11- Order
     12- sells
     13
     14==== Type of trigger
     15- BEFORE DELETE
     16
     17Activated on the `Store` table.
     18
     19==== SQL Code
     20{{{#!sql
     21CREATE OR REPLACE FUNCTION prevent_store_deletion()
     22RETURNS TRIGGER
     23LANGUAGE plpgsql
     24AS $$
     25BEGIN
     26    -- Check whether the store has existing reports
     27    IF EXISTS ( SELECT 1 FROM report WHERE store_id = OLD.store_id ) THEN
     28        RAISE EXCEPTION 'Store % cannot be deleted because it has existing reports.', OLD.store_id;
     29    END IF;
     30    -- Check whether the store has products associated with it
     31    IF EXISTS ( SELECT 1 FROM sells WHERE store_id = OLD.store_id ) THEN
     32        RAISE EXCEPTION 'Store % cannot be deleted because it has existing product records.', OLD.store_id;
     33    END IF;
     34    RETURN OLD;
     35END;
     36$$;
     37
     38CREATE TRIGGER trg_prevent_store_deletion
     39BEFORE DELETE
     40ON store
     41FOR EACH ROW
     42EXECUTE FUNCTION prevent_store_deletion();
     43
     44}}}
     45
     46=== Logic explanation
     47
     48Before a store is deleted, the trigger:
     49
     50**1.** Identifies the store using OLD.store_id.
     51**2.** Checks whether the store has any reports in the REPORT table.
     52**3.** Checks whether the store has any products associated with it through sells.
     53**4.** If any historical records exist, the deletion is rejected.
     54**5.** If no dependent records exist, the deletion is allowed.
     55
     56=== Reason for trigger
     57
     58This trigger is useful because:
     59
     60- It protects historical business data.
     61- It prevents accidental deletion of stores with existing records.
     62- It maintains referential and business data integrity.
     63- It ensures that important reports and sales history are not lost.