Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql prevent negative numbers

Tags:

mysql

Is their an int field in mysql where negative numbers are not allowed? or more specifically if a negative number is inserted into the field it will insert a zero. I ask this because we have a scoring system and we don't allow people to have negative scores. So if their score does reach bellow zero, it will just insert a zero instead. I'm trying to do this without having to query the user's score to check if it will fall bellow zero.

like image 296
user962449 Avatar asked Jan 09 '12 20:01

user962449


1 Answers

In addition to the DDL change (INT UNSIGNED) that others have recommended, I'd also change your application logic. You say:

I'm trying to do this without having to query the user's score to check if it will fall bellow zero.

You don't have to explicitly check in a separate query:

UPDATE your_table
   SET score = GREATEST(score + ?, 0) -- This '?' is the adjustment to the score
 WHERE user_id = ?

Now your application cannot UPDATE score to fall below zero, nor will it generate errors or warnings depending on the SQL mode.

like image 182
pilcrow Avatar answered Sep 24 '22 06:09

pilcrow