PostgreSQL - next serial value in a table

后端 未结 3 547
鱼传尺愫
鱼传尺愫 2021-01-03 19:09

I have a simple question, suppose we have a table:

 id   A   B
 1   Jon  Doe
 2   Foo  Bar

Is there a way to know, which is the next id\'s

3条回答
  •  青春惊慌失措
    2021-01-03 19:52

    If you want to claim an ID and return it, you can use nextval(), which advances the sequence without inserting any data.

    Note that if this is a SERIAL column, you need to find the sequence's name based on the table and column name, as follows:

    Select nextval(pg_get_serial_sequence('my_table', 'id')) as new_id;
    

    There is no cast-iron guarantee that you'll see these IDs come back in order (the sequence generates them in order, but multiple sessions can claim an ID and not use it yet, or roll back an INSERT and the ID will not be reused) but there is a guarantee that they will be unique, which is normally the important thing.

    If you do this often without actually using the ID, you will eventually use up all the possible values of a 32-bit integer column (i.e. reach the maximum representable integer), but if you use it only when there's a high chance you will actually be inserting a row with that ID it should be OK.

提交回复
热议问题