What is a sequence (Database)? When would we need it?

后端 未结 3 1917
暗喜
暗喜 2020-11-29 02:40

Why would we create a sequence even if there is a primary key?

3条回答
  •  [愿得一人]
    2020-11-29 03:39

    Sequence will allow you to populate primary key with a unique, serialized number.

    It's different from a serial or auto_incremement primary key in the sense that:

    • It is an actual database object (you need to create it):

      sql> create sequence NAME_OF_YOUR_SEQUENCE;

    • You could assign independent permissions to it, to different database users:

      sql> grant select on NAME_OF_YOUR_SEQUENCE to NAME_OF_YOUR_USER;

    • You can use to have a unique number that is different among several tables (not just one). Say you have four tables with numeric primary keys, and you want unique numbers among those four tables. You could use a sequence for that, without having to worry about implementing locking mechanisms to do it 'by hand'.

    • You can change its number to any value you want with alter sequence

    • You can cycle through its numbers

      sql> create sequence NAME_OF_YOUR_SEQUENCE maxvalue 1500 cycle;

提交回复
热议问题