snippetsqlMinor
MySQL: How to decrement an unsigned int column?
Viewed 0 times
columnunsignedmysqldecrementhowint
Problem
I have a table with a column
I want to decrement the column by a number, if value after decrement is less than 1 then set it to 1. Like this:
This works fine, but if col1 is 0 or 1 or 2 and I try to do -3 then MySQL throws an error.
I've tried this and this but didn't worked.
unsigned int, let's name it col1.I want to decrement the column by a number, if value after decrement is less than 1 then set it to 1. Like this:
UPDATE `tbl1` SET `col1` = GREATEST(1, `col1`-3);This works fine, but if col1 is 0 or 1 or 2 and I try to do -3 then MySQL throws an error.
I've tried this and this but didn't worked.
Solution
You can use a
As @RDFozz described :
With the OP's listed code, col1 - 3 must be computed, and since it's an unsigned integer, the result must be an unsigned integer. This code prevents the computation from happening unless the result would actually be an unsigned integer.
UPDATE :
Another possible way as suggested by @kondybas
case clauseupdate tbl1 set col1 = (case when col1 <= 3 then 1 else (col1 - 3) end);As @RDFozz described :
With the OP's listed code, col1 - 3 must be computed, and since it's an unsigned integer, the result must be an unsigned integer. This code prevents the computation from happening unless the result would actually be an unsigned integer.
UPDATE :
Another possible way as suggested by @kondybas
update tbl1 set col1 = IF(col1<=3, 1, col1-3);Code Snippets
update tbl1 set col1 = (case when col1 <= 3 then 1 else (col1 - 3) end);update tbl1 set col1 = IF(col1<=3, 1, col1-3);Context
StackExchange Database Administrators Q#206050, answer score: 6
Revisions (0)
No revisions yet.