How to fix all postgres sequence numbers in a database

Create this stored procedure:

CREATE OR REPLACE FUNCTION "reset_sequence" (tablename text, columnname text, sequence_name text) RETURNS "pg_catalog"."void" AS
$body$
DECLARE
BEGIN

EXECUTE 'SELECT setval( ''' || sequence_name || ''', ' || '(SELECT MAX(' || columnname || ') FROM ' || tablename || ')' || ')';
END;
$body$ LANGUAGE 'plpgsql';

Then, run this query:

select table_name || '_' || column_name || '_seq', reset_sequence(table_name, column_name, table_name || '_' || column_name || '_seq') from information_schema.columns where column_default like 'nextval%';

This entry was posted in Uncategorized. Bookmark the permalink.

Comments are closed.