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
  • 248,760
  • 80
  • 417
  • 510
Mafys Grif
  • 507
  • 1
  • 10
  • 23

2 Answers2

3

this will work:

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

and

`updated_at` = '2019-04-17 23:07:11'
nikhil sugandh
  • 3,422
  • 4
  • 16
  • 29
  • 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
  • 248,760
  • 80
  • 417
  • 510