Gaps between primary key id in sql table

后端 未结 2 933
旧巷少年郎
旧巷少年郎 2020-12-11 12:36

I have a table which is:

CREATE SEQUENCE id_seq;
CREATE TABLE public.\"UserInfo\"
(
  id bigint NOT NULL DEFAULT nextval(\'id_seq\'),
  phone text,
  passwor         


        
相关标签:
2条回答
  • 2020-12-11 12:56

    When generating an artificial primary key of this type it's important to clearly understand that the value of the primary key has no meaning. I'll emphasize that point again - THE VALUE OF THE KEY HAS NO MEANING, and any "meaning" which is ascribed to it by developers, managers, or users is incorrect. It's a value which is unique, non-null, and unchanging - that's it. It does not matter what the number is. It does not matter if it's in some "order" relative to other keys in the table. Do not fall into the trap of believing that these values need to be ordered, need to be increasing, or must in some other manner conform to some external expectations of "how they should look".

    Unique. Non-null. Unchanging. That's all you know, and all you need know.

    Best of luck.

    0 讨论(0)
  • 2020-12-11 13:15

    This is the way sequences work.

    Important: To avoid blocking concurrent transactions that obtain numbers from the same sequence, a nextval operation is never rolled back; that is, once a value has been fetched it is considered used and will not be returned again. This is true even if the surrounding transaction later aborts, or if the calling query ends up not using the value.

    As pointed out in the comments there's no harm in having gaps in sequences. If you delete some rows in your table for what ever reason you are creating gaps in your primary key values and you wouldn't normally bother with resetting them to make them sequential.

    If you insist on creating a gapless sequence, read this article: http://www.varlena.com/GeneralBits/130.php and be prepared for slow inserts.

    0 讨论(0)
提交回复
热议问题