Skip to content

Instantly share code, notes, and snippets.

@jenseng
Created June 4, 2020 18:35
Show Gist options
  • Save jenseng/465426eeecc4dad694fb87b2db2dd11e to your computer and use it in GitHub Desktop.
Save jenseng/465426eeecc4dad694fb87b2db2dd11e to your computer and use it in GitHub Desktop.
identiception: reset all IDENTITY columns in postgres
# a query that finds all IDENTITY columns and then outputs
# queries that find the max value for each table and then output
# an appropriate alter table call for each one
# which we then run 3x through psql 😅🤯
#
# this assumes you have appropriate PG* variables set up, e.g.
# PGDATABASE=mydb
# PGHOST=localhost
# ...
cat<<EOF|psql -t -A|psql -t -A|psql -q
SELECT
'SELECT
''ALTER TABLE "' || table_name || '"
ALTER COLUMN "' || column_name || '"
RESTART '' || "' || column_name || '" + 1 || '';''
FROM "' || table_name || '"
ORDER BY "' || column_name || '" DESC LIMIT 1;'
FROM information_schema.columns
WHERE is_identity = 'YES' AND table_schema = 'public';
EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment