3

I have a query:

update `shops` set
    `points` = `points` - 2,
    `updated_at` = '2019-04-17 23:07:11'
where `id` = 4;

Column points have a column type: BIGINT(20).

Now in record I have value 62. When I run the above query I get this error:

SQLSTATE[22003]: Numeric value out of range: 1690 BIGINT UNSIGNED value is out of range in '(`database`.`shops`.`points` - 2)'

Is different.

Salman A
  • 262,204
  • 82
  • 430
  • 521
Mafys Grif
  • 557
  • 3
  • 13
  • 30

2 Answers2

3

this will work:

 set `points` = `points` - cast(2 AS SIGNED)

and

`updated_at` = '2019-04-17 23:07:11'
Nikhil S
  • 3,786
  • 4
  • 18
  • 32
  • 2
    Not sure how that would work. It would still try to insert a -2 into a column that is an `unsigned` datatype. https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=8d07f56083557e4b336374dc02ddb77d – Shawn Apr 17 '19 at 20:43
3

You cannot store negative values in an unsigned integer. The safer solution is to check the operands before performing the subtraction:

SET points = CASE WHEN points >= 2 THEN points - 2 ELSE 0 END

Or simply:

SET points = points - LEAST(points, 2)
Salman A
  • 262,204
  • 82
  • 430
  • 521