4

Quick newbie MySQL question. What would be the simplest way to ensure that the minimum value of a given field is 0?

Basically, we have a script that runs automatically and subtracts an integer value from the value of a field every 15 minutes--but we want any entry that gets to 0 to stay at 0 and not go negative.

This could be simply done with a loop in PHP but I'm trying to limit calls to the database...

Is there a simple way to either make the minimum value for a field 0 or make it so any negative value put in that field automatically becomes 0?

Thanks!

2
  • Just change your update query to look for values in the specified field that are greater then 0, or better yet, greater then the amount you are about to subtract.
    – kmfk
    Aug 5, 2010 at 17:21
  • Wow. So simple. I always forget that you can use conditionals in the WHERE clause. Thanks a lot!
    – user405056
    Aug 5, 2010 at 18:02

4 Answers 4

6

Have you tried a simple conditional "WHERE" or is the problem more complex than that?

UPDATE mytable SET mycolumn=mycolumn-1 WHERE mycolumn>0
0
3

you can set UNSIGNED attribute for your field. mysql will generate an error if you try to set this field to something < 0.

2
  • Nope. No error, just a warning. MySQL will still happilly do the subtraction. on a basic unsigned int field, 0 - 1 = 4294967295
    – Marc B
    Aug 5, 2010 at 22:04
  • yes, just a warning, but the row is inserted with 0 instead of the negative value. just tested it on mysql 5.1.41-3ubuntu12.6, int(10) unsigned NOT NULL column Aug 6, 2010 at 7:52
2

You could add the logic to your script to not subtract from the value if the value is already zero...

An update trigger that corrects negative values, setting them to zero is another idea.

0

Common way to do this would be CHECK constraint but MySQL does not support that.

So either make the column unsigned and/or make sure that in your application logic you are subtracting the value only when it is > 0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.