Skip to content

Instantly share code, notes, and snippets.

@cunneen
Created August 20, 2014 03:25
Show Gist options
  • Save cunneen/01c9170dfdd863286080 to your computer and use it in GitHub Desktop.
Save cunneen/01c9170dfdd863286080 to your computer and use it in GitHub Desktop.
Mimicking Check Constraints in MySQL
-- Modified from: http://stackoverflow.com/a/14248038/956779
-- Add a BEFORE INSERT constraint that only allows values between 1 and 5
DELIMITER $$
CREATE TRIGGER `test_before_insert` BEFORE INSERT ON cheese_shop.items
FOR EACH ROW
BEGIN
IF (NEW.ratings > 5 OR NEW.ratings < 1) THEN
SIGNAL SQLSTATE '12345'
SET MESSAGE_TEXT = 'check constraint on items.ratings failed';
END IF;
END$$
DELIMITER ;
-- Add a BEFORE UPDATE constraint that only allows values between 1 and 5
DELIMITER $$
CREATE TRIGGER `test_before_update` BEFORE UPDATE ON cheese_shop.items
FOR EACH ROW
BEGIN
IF (NEW.ratings > 5 OR NEW.ratings < 1) THEN
SIGNAL SQLSTATE '12345'
SET MESSAGE_TEXT = 'check constraint on items.ratings failed';
END IF;
END$$
DELIMITER ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment