Last active
September 13, 2023 13:19
-
-
Save aliemre/a689ced32e8a9b26f1ee422f232b2ffc to your computer and use it in GitHub Desktop.
PostgreSQL Sync Sequence for Duplicate Key Error
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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