2

After an import to a database through a tool like Postico, or other, the ID sequence for tables fall out of sync.

I've learnt that I can fix this by running

SELECT pg_catalog.setval(pg_get_serial_sequence('table_name', 'id'), (SELECT MAX(id) FROM table_name)+1);

but how would I do this for all tables, without having to run the same command for each?

1 Answer 1

2

I've actually found an answer.

Create a file reset.sql with this as the content:

SELECT 'SELECT SETVAL(' ||
       quote_literal(quote_ident(PGT.schemaname) || '.' || quote_ident(S.relname)) ||
       ', COALESCE(MAX(' ||quote_ident(C.attname)|| '), 1) ) FROM ' ||
       quote_ident(PGT.schemaname)|| '.'||quote_ident(T.relname)|| ';'
FROM pg_class AS S,
     pg_depend AS D,
     pg_class AS T,
     pg_attribute AS C,
     pg_tables AS PGT
WHERE S.relkind = 'S'
    AND S.oid = D.objid
    AND D.refobjid = T.oid
    AND D.refobjid = C.attrelid
    AND D.refobjsubid = C.attnum
    AND T.relname = PGT.tablename
ORDER BY S.relname;

Run this file as

psql -h yourdb.yourhost.com -U mysecretuser -Atq -f reset.sql -o temp

Then run the output as

psql -h yourdb.yourhost.com -U mysecretuser -f temp

And finally

rm temp
Sign up to request clarification or add additional context in comments.

2 Comments

Running the first command, I get the error: reset.sql: No such file or directory
@kunambi You have to create the file with the content shared at the top of the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.