Skip to content

Instantly share code, notes, and snippets.

@nathansgreen
Last active January 24, 2024 23:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathansgreen/f4956e64584b3bb0ff68dd2f456313d5 to your computer and use it in GitHub Desktop.
Save nathansgreen/f4956e64584b3bb0ff68dd2f456313d5 to your computer and use it in GitHub Desktop.
Postgres Sequence Bulk Increment
-- I needed a way to safely pull a bunch of sequence values to my client in order to bulk
-- insert many thousands of rows. I'm doing this because I don't want to use 128-bit keys.
-- I found this:
-- https://www.depesz.com/2008/03/20/getting-multiple-values-from-sequences/
select pg_advisory_lock(123);
alter sequence seq increment by 1000;
select nextval('seq');
alter sequence seq increment by 1;
select pg_advisory_unlock(123);
-- note that if the sequence's `cache` value is > 1 this will end up
-- setting the sequence value to `nextval + increment * cache`
create or replace function multi_nextval(seqname text, increment int4)
returns bigint as $$
declare
seq text;
lock bigint;
reply bigint;
begin
select quote_ident(seqname) into seq;
select hashtextextended(seqname, 883669774654) into lock;
perform pg_advisory_lock(lock);
execute 'alter sequence ' || seq || ' increment by ' || increment::text;
reply := nextval(seqname);
execute 'alter sequence ' || seq || ' increment by 1';
perform pg_advisory_unlock(lock);
return reply;
end
$$ language 'plpgsql';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment