I can’t find a way to apply an ‘advanced’ query-based constraint.
For example, with the following fictitious schema, how can I enforce that the total percentage of Bob’s daily activities does not exceed 100%?
I’ve already looked into trigger constraints but I don’t think they’re going to do what I want (abort the INSERT/UPDATE if some criteria is met).
Thanks for reading my question and any help you can offer.
create table employee (
id serial PRIMARY KEY,
name varchar(100) NOT NULL
);
create table work_day (
employee_id integer references employee(id) NOT NULL,
percentage integer NOT NULL CHECK (percentage > 0 and percentage <= 100),
activity varchar(100) NOT NULL
);
INSERT INTO employee (name) VALUES ('bob');
-- Bob spends 50% of the day slacking, 20% eating and 30% working (total = 100%)
INSERT INTO work_day (employee_id, percentage, activity) VALUES (1, 50, 'slacking');
INSERT INTO work_day (employee_id, percentage, activity) VALUES (1, 20, 'eating');
INSERT INTO work_day (employee_id, percentage, activity) VALUES (1, 30, 'working');
-- This should be invalid!!! 100% of Bob's time has already been allocated
INSERT INTO work_day (employee_id, percentage, activity) VALUES (1, 10, 'invalid');
A pl/pgsql-based constraint trigger is what you want. sum() the thing, and check if it is within the defined bounds. If not, raise an exception and the statement will be cancelled.
Alternatively, have a normal trigger store/update the total activity in the employee table, and place a constraint on the latter.