PostgreSQL - next serial value in a table

后端 未结 3 488
鱼传尺愫
鱼传尺愫 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:33

    SELECT currval('names_id_seq') + 1;

    See the docs

    However, of course, there's no guarantee that it's going to be your next value. What if another client grabs it before you? You can though reserve one of the next values for yourself, selecting a nextval from the sequence.

    0 讨论(0)
  • 2021-01-03 19:35

    To get the current value of a sequence without affecting it or needing a previous insert in the same session, you can use;

    SELECT last_value FROM tablename_fieldname_seq;
    

    An SQLfiddle to test with.

    Of course, getting the current value will not guarantee that the next value you'll get is actually last_value + 1 if there are other simultaneous sessions doing inserts, since another session may have taken the serial value before you.

    0 讨论(0)
  • 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.

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