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.