Restart All PostgreSQL Sequences with ALTER SEQUENCE
Restarting All PostgreSQL Sequences with SQL Script
Database administrators often face challenges with PostgreSQL sequences, especially after data has been deleted or when tables have been re-imported. Sequences drive the generation of auto-incrementing values (like primary keys using SERIAL or BIGSERIAL), and sometimes they need to be reset or restarted.
This guide covers a simple SQL script that restarts all PostgreSQL sequences across your database, making it easier to bring sequences back in sync with your table data.
Sample Code from Command Line
1-- Restarts all PostgreSQL sequences
2SELECT
3 'ALTER SEQUENCE ' || relname || ' RESTART;'
4FROM
5 pg_class
6WHERE
7 relkind = 'S';
Breakdown & Key Points
Breakdown of the SQL Query
System Catalog –
pg_class- PostgreSQL stores metadata about objects (tables, indexes, sequences) in system catalogs.
pg_classcontains details about relations, including sequences.
Filtering with
relkind = 'S'relkindidentifies the type of object stored.'S'means sequence. This filter ensures we only target sequences, not tables or indexes.
Generating
ALTER SEQUENCEStatements- The query dynamically builds commands like:
1ALTER SEQUENCE my_table_id_seq RESTART; - Each row returned is a ready-to-run SQL command that resets a specific sequence.
- The query dynamically builds commands like:
How to Use It
- Run the query to generate the SQL commands.
- Copy the output, which will be a list of
ALTER SEQUENCE ... RESTART;statements. - Execute the generated SQL statements to reset all sequences.
Note: Restarting a sequence sets its counter back to the initial value (default 1 unless specified otherwise). If your target table already has data, you may need to adjust the sequence with RESTART WITH <number> so it doesn’t cause primary key conflicts.
Key Points and Insights
- Database Versions: Works across PostgreSQL 8.4 to 13, ensuring compatibility with most environments.
- Re-imported Data Fix: Useful after bulk inserts, imports, or restores, where sequence values fall out of sync with table data.
- Alternative Reset: Instead of restarting, you can use:to align a sequence with the current maximum value in its table.
1ALTER SEQUENCE my_table_id_seq RESTART WITH <next_id>; - DBA Tip: Always double-check existing data before restarting, to avoid duplicate key errors.
Example Use Case
Imagine you truncated or reloaded data into a table with a SERIAL primary key. The table’s actual data might have IDs up to 500, but the sequence may still be ready to generate 1. Restarting it would cause conflicts. In such cases, combine this restart script with sequence alignment commands like:
1SELECT setval(pg_get_serial_sequence('table_name', 'id'), COALESCE(MAX(id), 1)) FROM table_name;
References
Posts in this series
- How Many Connections Can Your PostgreSQL Database Handle?
- PostgreSQL Backend Connections via pg_stat_database
- Identifying Blocking PostgreSQL Queries using pg_stat_activity
- List PostgreSQL Databases by Size with Access Check
- Assess PostgreSQL Database Sizes Quickly and Easily
- Unveiling Your PostgreSQL Server - A Diagnostic Powerhouse
- Keep Your PostgreSQL Database Clean, Identify Idle Connections
- Query the PostgreSQL Configuration
- PostgreSQL Recovery Monitoring: Essential SQL Insights
- Restart All PostgreSQL Sequences with ALTER SEQUENCE
- Monitor Running Queries in PostgreSQL using pg_stat_activity
- Monitor PostgreSQL Active Sessions with pg_stat_activity
- PostgreSQL Error Handling Settings via pg_settings
- PostgreSQL File Location Settings Query via pg_settings
- PostgreSQL Lock Management Settings via pg_settings
- PostgreSQL Logging Configuration Query via pg_settings
- Monitor PostgreSQL Memory Settings with pg_settings
- PostgreSQL Table Row Count Estimates with SQL
- List PostgreSQL Tables by Size with SQL
- PostgreSQL WAL Settings Query Guide
- PostgreSQL SSL Settings Query Guide
- PostgreSQL Statistics Settings Query Guide
- PostgreSQL Resource Settings Query Guide
- PostgreSQL Replication Settings Query Guide
- PostgreSQL Query Planning Settings Query Guide
- PostgreSQL Preset Options Settings Query Guide
- PostgreSQL Miscellaneous Settings Query Guide
- Count PostgreSQL Sessions by State with SQL
- Kill Idle PostgreSQL Sessions with SQL
- Grant SELECT on All Tables in PostgreSQL
- Identify Insert-Only Tables in PostgreSQL
- Detect Soft Delete Patterns in PostgreSQL
- List PostgreSQL Object Comments with SQL
- List Foreign Key Constraints in PostgreSQL
- List PostgreSQL Enum Types and Their Values with SQL
- List All Views in a PostgreSQL Database with SQL
- Find PostgreSQL Tables Without a Primary Key
- List PostgreSQL Partitioned Tables with SQL