I’m trying to add a constraint to a table by checking that the sum of a value is < 100.
This is my schema:
CREATE TABLE Works (
eid INTEGER,
did INTEGER,
pct_time INTEGER,
PRIMARY KEY (eid,did),
FOREIGN KEY (eid) REFERENCES Employee(eid),
FOREIGN KEY (did) REFERENCES Dept(did)
);
I need to check that the sum of pct_time for each eid is <= 100.
For example
eid --- did ---- pct_time
0 ----- a ------- 50
0 ----- d ------- 40
0 ----- c ------- 20
1 ----- a ------- 90
1 ----- b ------- 10
2 ----- d ------- 40
2 ----- a ------- 20
Here, it should have errored when I added the 3rd entry for eid 0 as the sum > 100.
It would have been fine for eid 1 and 2 as pct_time <= 100
How can this be done?
So far all I’ve done is
ALTER TABLE Works
ADD CONSTRAINT c1
CHECK SUM(pct_time) < 100
You should use a trigger for this. Make it check if
SELECT SUM(pct_time) FROM Works GROUP BY eidhas any values that will go over 100 after your insert. If it is the case, throw an error.Are you familiar with triggers? What database system are you using?
EDIT:
Check out the documentation for triggers here. Basically what you want is something like this:
Then your
check_sum_work()procedure will check if any SUM(pct_time) > 100.Here is the documentation for trigger procedures, take note of the
NEWspecial variable which allows you to single out the element being inserted. So you’ll want toSELECT SUM(pct_time) FROM Works WHERE eid = NEW.eidand see if that sum +NEW.pct_timeis greater than 100.This might sounds pretty complicated if you’ve never seen triggers before, but it’s actually a pretty powerful mechanism that you’ll learn to appreciate. 🙂
Here is another example of PostgeSQL triggers being used.