I have a table called BFFs, that stores userID, and best friend's userID and I would like to restrict that table to have exactly 3 number of best friends for each different user.
I mean if the table structre is:
BFFs(userID, userID)
and records are:
(3286, 1212)
(3286, 4545)
(3286, 7878)
And in that case, if user with ID 3286 should not be allowed to have a new record such as (3286, xyzt).
I wrote this trigger but I'm not sure:
CREATE TRIGGER BFFControl
BEFORE INSERT ON BFFs
FOR EACH ROW
DECLARE
numberOfBFFs INTEGER;
max_BFFs INTEGER := 3;
BEGIN
SELECT COUNT(*) INTO numberOfBFFs
FROM BFFs
WHERE sender =: NEW.sender
IF :OLD.sender =: NEW.sender THEN
RETURN;
ELSE
IF numberOfBFFs >= max_BFFs THEN
RAISE_APPLICATION_ERROR(-20000, 'Users are allowed to have at most thre friends.');
END IF;
END IF;
END;
/
How should I restrich this on relational tables through assertions or triggers ?
Thanks