Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to backup Sequences in Postgresql?

Can we take the backup of sequences and use it in other databases?

like image 556
akhilesh kedarisetty Avatar asked May 10 '26 22:05

akhilesh kedarisetty


2 Answers

Below SQL will return the list of SQL statement that can be executed on target to Reset value of sequence

SELECT 'ALTER SEQUENCE ' || c.relname || ' RESTART WITH ' || nextval(c.relname::regclass) || ';' 
FROM pg_class c WHERE c.relkind = 'S';
like image 163
Arjun Vachhani Avatar answered May 13 '26 14:05

Arjun Vachhani


SELECT 'ALTER SEQUENCE ' || s.relname || ' RESTART WITH ' || t.reltuples + 1 || ';'
FROM pg_class s 
  JOIN pg_depend d ON d.objid = s.oid 
  JOIN pg_class t ON d.objid = s.oid AND d.refobjid = t.oid 
  JOIN pg_attribute a ON (d.refobjid, d.refobjsubid) = (a.attrelid, a.attnum)
  JOIN pg_namespace n ON n.oid = s.relnamespace 
WHERE s.relkind = 'S' AND n.nspname = 'public'
like image 33
Jhonny Ramirez Zeballos Avatar answered May 13 '26 16:05

Jhonny Ramirez Zeballos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!