Skip to content
Advertisement

PostgreSQL Update and return

Let’s say I have a table called t in Postgres:

I need to update the state of a row by ID, while also returning some things:

  • The old state
  • The remaining number of rows in the same group that have state = 0

I’ve got a query to do this as follows:

However, it seems like the subquery within RETURNING is executed before the update has completed, leaving me with a remaining_count that is off by 1.

Additionally, I’m not sure how this behaves when concurrent queries are run. If we update two of these rows at the same time, is it possible that they would both return the same remaining_count?

Is there a more elegant solution to this? Perhaps some sort of window/aggregate function?

Advertisement

Answer

The subquery is indeed run without seeing the change from the UPDATE, because it’s running before the UPDATE has committed, and therefore it’s not visible. Nevertheless, it’s an easy fix; just add a where clause to filter out the ID you just updated in the subquery, making your query something like this:

Concurrency-wise, I’m not sure what the behavior would be, TBH; best I can do is point you at the relevant docs.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement