Last active
November 9, 2021 07:27
-
-
Save redsfyre/88103a98096a665f17cd429180aa9b0a to your computer and use it in GitHub Desktop.
While I was creating postgresql table partitions, I realized that I needed to move/copy the old id sequence to the new table. We can do this with the following query
This file contains 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
postgres_test_db=# select last_value from old_table_id_seq; | |
last_value | |
------------ | |
2084740 | |
(1 row) | |
postgres_test_db=# select last_value from new_table_id_seq; | |
last_value | |
------------ | |
1 | |
(1 row) | |
-- In order to avoid errors, the id must be able to continue from where it left off. | |
-- For this, we need to set the last value from the old sequence to the new one. | |
-- We can get this id value in two different ways; | |
-- First one; | |
SELECT pg_catalog.setval( | |
'new_table_id_seq', | |
(SELECT last_value FROM old_table_id_seq), | |
true | |
); | |
-- Second one; | |
SELECT pg_catalog.setval( | |
'new_table_id_seq', | |
(SELECT max(id) FROM old_table), | |
true | |
); | |
-- Technically they both do the same job but getting it directly from id_seq made more sense to me | |
-- After running setval we can verify that the old id is written to the new sequence; | |
postgres_test_db=# select last_value from new_table_id_seq; | |
last_value | |
------------ | |
2084740 | |
(1 row) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment