Decrementing table field value based on supplied input

I have a record with a integer field score and I want to perform a decrement update operator like instead of SET "score" = q0."score" + $1 I want to do SET "score" = q0."score" - $1.

I looked up update operator with inc but it doesn’t seem get the expected output that I want

  defp reset_vote_multi(multi, query, existing_vote) do
    |> Multi.update_all(
      inc: [score: existing_vote.score]

The problem with my code above, since update/3 will only perform a decrement if existing_vote.score is negative which I don’t want to do.

Is there a way to perform a decrement on the current field value? I would like to ask for help or ideas.

Thank you.

have you tried writing this part as

      inc: [score: -existing_vote.score]


It works. I thought it would have some unexpected outcome by doing this (explicitly making the existing score negative/postive by adding - sign)

Don’t be afraid to experiment :slight_smile:

1 Like