Upon occasion, you want to get the current value of all the sequences in the database. For example, you may have fields that are integer rather than bigint, and you’re concerned how close you are to overflowing one of them (since sequences are bigint and will happily crash through the size of a 32-bit integer).

Unfortunately, currval() requires that you have actually accessed the sequence value using nextval() in the current session… but you don’t want to increment the value, just test it!

Here’s a cheap and cheerful PL/pgSQL function that returns all of the current sequence values:

1CREATE OR REPLACE FUNCTION sequence_values() RETURNS TABLE(name text, value bigint) AS $sequence_values$
2DECLARE
3 nsp_name TEXT;
4 seq_name TEXT;
5BEGIN
6 FOR nsp_name, seq_name IN
7 SELECT nspname::text, relname::text
8 FROM pg_class
9 JOIN pg_namespace
10 ON pg_class.relnamespace = pg_namespace.oid WHERE relkind='S'
11 LOOP
12 RETURN QUERY EXECUTE 'SELECT ''' || nsp_name || '.' || seq_name || '''::text, last_value FROM "' || nsp_name || '"."' || seq_name || '"';
13 END LOOP;
14END;
15$sequence_values$
16LANGUAGE plpgsql;