Skip to content

Instantly share code, notes, and snippets.

@aliemre
Last active September 13, 2023 13:19
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 aliemre/a689ced32e8a9b26f1ee422f232b2ffc to your computer and use it in GitHub Desktop.
Save aliemre/a689ced32e8a9b26f1ee422f232b2ffc to your computer and use it in GitHub Desktop.
PostgreSQL Sync Sequence for Duplicate Key Error
# For Single Table
SELECT setval('public."upload_file_morph_id_seq"',
(SELECT MAX(id) FROM public.upload_file_morph)
);
# For All Tables
DO $$
DECLARE
i TEXT;
BEGIN
FOR i IN (SELECT tbls.table_name FROM information_schema.tables AS tbls INNER JOIN information_schema.columns AS cols ON tbls.table_name = cols.table_name WHERE tbls.table_catalog='YOUR_DATABASE_NAME' AND tbls.table_schema='public' AND cols.column_name='id') LOOP
EXECUTE 'SELECT setval(''"' || i || '_id_seq"'', (SELECT MAX(id) FROM ' || quote_ident(i) || '));';
END LOOP;
END $$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment