1

using this query i can easily deduct the payment to the remaining balance

let say that my rem_balance is 3000 and my payment is 5000 so basically the change would be 2000.

UPDATE tbl_users SET rem_balance = (rem_balance - '5000') WHERE user_id = '2017001002'

but since i use this query what happen is the rem_balance updates to -2000 what i wanted to achieve is that if payment is > rem_balance, rem_balance becomes 0 and it will separate the change.

Lion Smith
  • 647
  • 3
  • 16
  • 48

1 Answers1

2

Something like this should work

UPDATE tbl_users 
SET rem_balance = (CASE WHEN rem_balance < 5000 THEN 0 ELSE rem_balance - 5000 END)
WHERE user_id = '2017001002'

Please be aware of the fact that you use implicit conversion in your SQL ('5000' instead of 5000). It is a bad habit and it can harm performance of your queries in certain cases. For example, if tbl_users.user_id is integer as well then the update will be unable to use indexes to search the row with the specific user_id and it will do a sequential scan which is very slow.

Radim Bača
  • 10,646
  • 1
  • 19
  • 33