So, I’m using MySQL, and having a table where I’m restricting the ability to insert/update records to have overlaps, but end_date is allowed to be NULL.
Since MySQL doesn’t have extensions around this, the easiest way to do it is with a trigger.
I have the following triggers:
CREATE TRIGGER memberships_insert_overlap
BEFORE INSERT
ON team_memberships FOR EACH ROW
BEGIN
DECLARE rowcount INT;
SELECT COUNT(*) INTO rowcount FROM team_memberships
WHERE person_id = NEW.person_id
AND (NEW.start_date <= COALESCE(end_date, '9999-12-31')) and (COALESCE(NEW.end_date, '9999-12-31') >= start_date)
AND (NEW.start_date <= COALESCE(NEW.end_date, '9999-12-31')) and (start_date <= COALESCE(end_date, '9999-12-31'));
IF rowcount > 0 THEN
signal sqlstate '45000' set message_text = 'overlap not allowed team_memberships.no_overlap';
END IF;
END;
CREATE TRIGGER memberships_update_overlap
BEFORE UPDATE
ON team_memberships FOR EACH ROW
BEGIN
DECLARE rowcount INT;
SELECT COUNT(*) INTO rowcount FROM team_memberships
WHERE person_id = NEW.person_id AND id != OLD.id
AND (NEW.start_date <= COALESCE(end_date, '9999-12-31')) and (COALESCE(NEW.end_date, '9999-12-31') >= start_date)
AND (NEW.start_date <= COALESCE(NEW.end_date, '9999-12-31')) and (start_date <= COALESCE(end_date, '9999-12-31'));
IF rowcount > 0 THEN
signal sqlstate '45000' set message_text = 'overlap not allowed team_memberships.no_overlap';
END IF;
END;
I’m getting the typical/expected (MyXQL.Error) (1644) overlap not allowed team_memberships.no_overlap
I feel like there’s probably something I’m missing with what sqlstate should be set to for “emulating” a constraint, or that there’s some place in MyXQL where I can register a custom handler.
Anyone have any ideas?
I’d rather not litter my code w/ error-catching statements wherever we do inserts/updates.
EDIT: I should note, I’m not concerned about the trigger logic itself. That works fine. I’m wondering if there’s a better way to wrap up this interface.






















