First way: use LEAST()
and GREATEST()
:
UPDATE t SET someNum=GREATEST(-3,LEAST(3,someNum+2)) WHERE dataId=78225;
This is the most easy way because you'll store all the logic inside one UPDATE
query.
Second way: create trigger:
DELIMITER //
CREATE TRIGGER catCheck BEFORE UPDATE ON t
FOR EACH ROW
BEGIN
IF NEW.someNum<-3 THEN
NEW.someNum=-3;
END IF;
IF NEW.someNum>3 THEN
NEW.someNum=3;
END IF;
END;//
DELIMITER ;
you can also replace IF
with CASE
- but I left that two separate constraints for -3
and 3
. The benefits here is - that DBMS will handle your data by itself - and you'll be able to pass data as it is and do not worry about ranges. But - there's weakness too: while in first case you can just change query text to adjust desired range, in second case you'll have to re-create trigger again if you'll want to change that constraints (so, less flexibility).
Also you may want to check your data not only on UPDATE
statements, but on INSERT
too.