How to check a sequence efficiently for used and unused values in PostgreSQL

前端 未结 4 1748
暖寄归人
暖寄归人 2020-12-21 11:36

In PostgreSQL (9.3) I have a table defined as:

CREATE TABLE charts
( recid serial NOT NULL,
  groupid text NOT NULL,
  chart_number integer NOT NULL,
  \"tim         


        
4条回答
  •  既然无缘
    2020-12-21 12:10

    In PostgreSQL, a SEQUENCE ensures the two requirements you mention, that is:

    1. No repeats
    2. No changes once assigned

    But because of how a SEQUENCE works (see manual), it can not ensure no-skips. Among others, the first two reasons that come to mind are:

    1. How a SEQUENCE handles concurrent blocks with INSERTS (you could also add that the concept of Cache also makes this impossible)
    2. Also, user triggered DELETEs are an uncontrollable aspect that a SEQUENCE can not handle by itself.

    In both cases, if you still do not want skips, (and if you really know what you're doing) you should have a separate structure that assign IDs (instead of using SEQUENCE). Basically a system that has a list of 'assignable' IDs stored in a TABLE that has a function to pop out IDs in a FIFO way. That should allow you to control DELETEs etc.

    But again, this should be attempted, only if you really know what you're doing! There's a reason why people don't do SEQUENCEs themselves. There are hard corner-cases (for e.g. concurrent INSERTs) and most probably you're over-engineering your problem case, that probably can be solved in a much better / cleaner way.

提交回复
热议问题