Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save arvindkumarbadwal/8a186779d58fc801b0289ff554cd3f3e to your computer and use it in GitHub Desktop.
Save arvindkumarbadwal/8a186779d58fc801b0289ff554cd3f3e to your computer and use it in GitHub Desktop.
Updating postgres sequence values from table
Step 1:
/* Create queries to set the sequences of the table with max of the table */
SELECT 'SELECT SETVAL(' ||
quote_literal(quote_ident(PGT.schemaname) || '.' || quote_ident(S.relname)) ||
', COALESCE(MAX(' ||quote_ident(C.attname)|| '), 1) ) FROM ' ||
quote_ident(PGT.schemaname)|| '.'||quote_ident(T.relname)|| ';'
FROM pg_class AS S,
pg_depend AS D,
pg_class AS T,
pg_attribute AS C,
pg_tables AS PGT
WHERE S.relkind = 'S'
AND S.oid = D.objid
AND D.refobjid = T.oid
AND D.refobjid = C.attrelid
AND D.refobjsubid = C.attnum
AND T.relname = PGT.tablename
ORDER BY S.relname;
Step 2:
// Fire all the queries output from step 1
Example: Output for user table
SELECT SETVAL('public.user_id_seq', COALESCE(MAX(id), 1) ) FROM public.user;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment