How to set sequence to value?, How to sequence set current value? In SQL / Postgresql

Dr. Viktor Walter-Tscharf1 MIN. LESEZEIT
How to set sequence to value?, How to sequence set current value? In SQL / Postgresql

In this article I will explain how to set a sequence to a specific value. This comes into handy when we want to restore a database and forgot to backup the sequence. Or if the ID as PK(primarily key) is matching a wrong range. Therefore we can modify the SQL SEQUENCES. Use the following commands to test.

Photo by Tobias Fischer on Unsplash

If you already have the SEQUENCE, which you want to modify or change you can jump to point 2 and replace test_seq with your name.

1.Create a SEQUENCE

CREATE SEQUENCE test_seq AS integer;

2.Change the start value of the SEQUENCE.

ALTER SEQUENCE test_seq RESTART WITH 181;

3.Modify the table where the SEQUENCE is used.

ALTER TABLE ONLY testTable1 ALTER COLUMN id SET DEFAULT nextval(‘test_seq’::regclass);

I hope the article helped. Happy coding!