Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save boubkhaled/59344b1da3700783a04fcb223c4f6555 to your computer and use it in GitHub Desktop.
Save boubkhaled/59344b1da3700783a04fcb223c4f6555 to your computer and use it in GitHub Desktop.
PostgreSQL Updating sequence values from table
-- Tested with PostgreSQL 16
-- Source: https://wiki.postgresql.org/wiki/Fixing_Sequences
SELECT
'SELECT SETVAL(' ||
quote_literal(quote_ident(sequence_namespace.nspname) || '.' || quote_ident(class_sequence.relname)) ||
', COALESCE(MAX(' ||quote_ident(pg_attribute.attname)|| '), 1) ) FROM ' ||
quote_ident(table_namespace.nspname)|| '.'||quote_ident(class_table.relname)|| ';'
FROM pg_depend
INNER JOIN pg_class AS class_sequence
ON class_sequence.oid = pg_depend.objid
AND class_sequence.relkind = 'S'
INNER JOIN pg_class AS class_table
ON class_table.oid = pg_depend.refobjid
INNER JOIN pg_attribute
ON pg_attribute.attrelid = class_table.oid
AND pg_depend.refobjsubid = pg_attribute.attnum
INNER JOIN pg_namespace as table_namespace
ON table_namespace.oid = class_table.relnamespace
INNER JOIN pg_namespace AS sequence_namespace
ON sequence_namespace.oid = class_sequence.relnamespace
ORDER BY sequence_namespace.nspname, class_sequence.relname;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment