Atomic UPDATE to increment integer in Postgresql

孤街浪徒 提交于 2019-12-21 04:56:35

问题


I'm trying to figure out if the query below is safe to use for the following scenario:

I need to generate sequential numbers, without gaps. As I need to track many of them, I have a table holding sequence records, with a sequence integer column.

To get the next sequence, I'm firing off the SQL statement below.

WITH updated AS (
  UPDATE sequences SET sequence = sequence + ? 
  WHERE sequence_id = ? RETURNING sequence
)
SELECT * FROM updated;

My question is: is the query below safe when multiple users fire this query at the database at the same time without explicitly starting a transaction?

Note: the first parameter is usually 1, but could also be 10 for example, to get a block of 10 new sequence numbers


回答1:


Yes, that is safe.

While one such statement is running, all other such statements are blocked on a lock. The lock will be released when the transaction completes, so keep your transactions short. On the other hand, you need to keep your transaction open until all your work is done, otherwise you might end up with gaps in your sequence.
That is why it is usually considered a bad idea to ask for gapless sequences.




回答2:


Unless I misunderstand the question, that's what the SERIAL data type is for:

https://www.postgresql.org/docs/8.1/static/datatype.html#DATATYPE-SERIAL



来源:https://stackoverflow.com/questions/40162952/atomic-update-to-increment-integer-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!