Postgres Sequence Reset Generator

Bulk imports, COPY and pg_restore write ids directly and leave serial and identity sequences behind, so the next INSERT fails with duplicate key value violates unique constraint. Paste your CREATE TABLE statements (or pg_dump output), or just list schema.table.column, and get correct setval() SQL that moves each sequence to MAX(id) + 1 - with empty tables starting at 1, quoted mixed-case names, shared sequences and identity columns handled. You can also generate a single DO block that fixes every sequence in a schema and a diagnostic query that lists the sequences that are behind. Everything runs in your browser.

Samples:
4 sequence-backed columns found
TableColumnSource
public.customersidbigserial
sales.ordersorder_ididentity (start 1000)
sales."OrderItems""ItemID"serial
public.audit_logidnextval('public.audit_log_id_seq')
  • No sequence-backed column in: public.settings.

Do more than postgres sequence reset generator — meet Chat2DB

Chat2DB is an AI-powered SQL client for Windows, macOS and Linux. Write SQL in natural language, format and optimize queries automatically, and manage MySQL, PostgreSQL, Oracle and 20+ other databases in one workspace.

Why Postgres sequences fall behind MAX(id)

A serial, bigserial or identity column only calls nextval() when the INSERT leaves the column out. Any load that writes the id itself - COPY from a CSV export, INSERT statements with explicit ids, a data-only pg_restore, logical replication, or a migration tool - fills the table without touching the sequence. The sequence still says 1 (or whatever it said before), so the first normal INSERT asks for an id that already exists and fails with ERROR: duplicate key value violates unique constraint "orders_pkey" - DETAIL: Key (id)=(1) already exists. It then fails again for id 2, 3 and so on, because every failed attempt still consumes a value.

setval and the is_called flag

setval(seq, n) is short for setval(seq, n, true): it marks n as already used, so the next nextval() returns n + 1. The popular one-liner SELECT setval(seq, MAX(id)) FROM t therefore works for tables with rows but breaks on an empty table, where MAX(id) is NULL (setval returns NULL and does nothing) or, with COALESCE(MAX(id), 0), fails because 0 is below the sequence's MINVALUE of 1. The generator uses setval(seq, COALESCE(MAX(id), 0) + 1, false) instead: is_called = false means the next nextval() returns exactly that value, which is MAX + 1 for a filled table and 1 for an empty one.

serial, identity and nextval() defaults

serial and bigserial create a sequence named table_column_seq that is OWNED BY the column, and GENERATED AS IDENTITY columns own an internal sequence too, so pg_get_serial_sequence('schema.table', 'column') finds both. Its first argument is parsed like SQL (mixed case must be written as '"Sales"."OrderItems"'), while the second is taken literally ('ItemID', not '"ItemID"'). A column that only has DEFAULT nextval('some_seq') without OWNED BY is invisible to pg_get_serial_sequence, so the generator uses the sequence name from the default directly, and the DO block follows the dependency from pg_attrdef. When several tables share one sequence, all of them are combined with GREATEST so one table does not rewind the sequence below another's ids.

Running the fix safely

Sequence changes are not transactional - a ROLLBACK does not undo setval - but wrapping the fix in BEGIN ... COMMIT together with LOCK TABLE ... IN EXCLUSIVE MODE still matters on a live system: the lock blocks INSERTs (while allowing reads) between reading MAX(id) and moving the sequence, so no session can grab a stale id in between. Run the diagnostic query first to see which sequences are behind, run the fix, then run the diagnostic again: every row should say ok.

How to use

  1. Paste CREATE TABLE / ALTER TABLE DDL (serial, bigserial, GENERATED AS IDENTITY and DEFAULT nextval() columns are detected), or one schema.table.column per line. Load a sample to see both formats.
  2. Choose the output: per-column setval statements, one DO block that fixes every sequence in the listed schemas, or a read-only diagnostic query. Optionally wrap it in a transaction, lock the tables against concurrent INSERTs, or never move a sequence backwards.
  3. Run the diagnostic query to see which sequences are behind, run the generated fix, then run the diagnostic again - every row should report ok and INSERTs stop failing with duplicate key errors.

Frequently asked questions

How do I fix "duplicate key value violates unique constraint" on a serial or identity column?

The sequence behind the column is lower than the ids already in the table, usually after an import that supplied explicit ids. Move it past the current maximum: SELECT setval(pg_get_serial_sequence('public.orders', 'id'), COALESCE(MAX(id), 0) + 1, false) FROM public.orders; The next INSERT then gets MAX(id) + 1. pg_get_serial_sequence works for serial, bigserial and GENERATED AS IDENTITY columns; for a column whose default is nextval('some_seq') without OWNED BY, pass the sequence name to setval directly.

Why use setval with false instead of SELECT setval(seq, MAX(id))?

The third argument is is_called. With true (the default) the value you pass counts as already used and the next nextval() returns value + 1; with false the next nextval() returns exactly the value. setval(seq, MAX(id)) returns NULL and changes nothing on an empty table, and setval(seq, COALESCE(MAX(id), 0)) fails with value 0 is out of bounds because the minimum is 1. setval(seq, COALESCE(MAX(id), 0) + 1, false) is correct in both cases: MAX + 1 for a filled table and 1 for an empty one.

How do I reset all sequences in a Postgres schema at once?

Use the DO block output. It reads pg_depend to find every sequence owned by a serial or identity column, plus sequences referenced only by a DEFAULT nextval(), computes the MAX of every column that uses each sequence, and calls setval for each one inside a single transaction, printing a NOTICE per sequence. Run the diagnostic query before and after to confirm. To browse the tables, check ids and run the script against a live database, Chat2DB is a free SQL client with an AI assistant - download it at https://chat2db.ai/download or use https://app.chat2db.ai.

More free SQL tools

SQL Formatter & Beautifier
Format and beautify SQL queries online with dialect-aware indentation and keyword casing.
SQL Validator & Syntax Checker
Check SQL syntax online for MySQL, PostgreSQL and more, with clear error messages.
SQL Minifier
Minify SQL by stripping comments and collapsing whitespace into a single line.
MySQL to PostgreSQL Converter
Convert MySQL DDL and queries to PostgreSQL syntax with a best-effort dialect translator.
CSV to SQL Converter
Turn CSV, TSV or pasted Excel data into SQL INSERT statements.
JSON to SQL Converter
Convert a JSON array of objects into SQL INSERT statements.
SQL IN Clause Generator
Paste a list of values and get a ready-to-use SQL IN (...) clause.
SQL Escape & Unescape
Escape single quotes and special characters for safe SQL string literals.
JDBC Connection String Builder
Build JDBC URLs for MySQL, PostgreSQL, SQL Server, Oracle, MariaDB and ClickHouse.
SQL Cheat Sheet
A practical SQL reference: joins, aggregation, window functions, DDL and dialect differences.
UUID Generator (v4 & v7)
Generate UUID v4 and time-ordered UUID v7 in bulk, as plain text, JSON, CSV or SQL.
Cron Expression Generator & Validator
Build and validate cron expressions with plain-English explanations and next run times.
PostgreSQL EXPLAIN Plan Visualizer
Turn EXPLAIN ANALYZE output into a readable plan tree with timings and tuning warnings.
PgBouncer Config Generator
Generate pgbouncer.ini and size connection pools from your app instances and CPU cores.
PostgreSQL Partition Table Generator
Generate RANGE, LIST and HASH partitioning DDL with child partitions and maintenance SQL.
pg_dump Command Generator
Build pg_dump and pg_restore commands with format, filter and parallel job options.
mysqldump Command Generator
Build mysqldump backup commands with scope, options and a matching restore command.
SQL Test Data Generator
Generate realistic fake rows as SQL INSERT statements, CSV or JSON, right in your browser.
PostgreSQL Config Calculator
Calculate tuned postgresql.conf settings from your RAM, CPU cores, connections and workload.
SQL DDL to Code Generator
Convert CREATE TABLE statements into TypeScript, Prisma, Drizzle, Go, JPA or SQLAlchemy models.
SQL Window Function Generator
Build ROW_NUMBER, RANK, LAG, LEAD and running-total OVER() clauses with PARTITION BY and frames.
Docker Compose PostgreSQL Generator
Generate a docker-compose.yml for PostgreSQL with volumes, healthchecks, init scripts and pgAdmin.
PostgreSQL Replication Config Generator
Generate streaming and logical replication config: postgresql.conf, pg_hba.conf, slots and pg_basebackup.
SQL Injection Checker
Scan code for SQL injection risks and rewrite unsafe queries with bound parameters.
SQL to ER Diagram Generator
Paste CREATE TABLE DDL and get an entity relationship diagram plus Mermaid erDiagram code.
Postgres Connection String Generator
Build PostgreSQL connection strings: libpq URI, DSN, JDBC, psycopg, SQLAlchemy, Npgsql and .env.
Postgres GRANT Statement Generator
Generate PostgreSQL GRANT, ALTER DEFAULT PRIVILEGES and REVOKE scripts for read-only or read-write roles.
Postgres COPY Command Generator
Build PostgreSQL COPY and psql \copy commands to import or export CSV with HEADER, DELIMITER, NULL and WHERE options.
Postgres CREATE INDEX Generator
Generate PostgreSQL CREATE INDEX statements: B-tree, GIN, GiST, BRIN, UNIQUE, CONCURRENTLY, partial WHERE, INCLUDE and expression indexes.
Postgres TO_CHAR Date Format Builder
Build PostgreSQL TO_CHAR date format patterns with live preview, presets and generated TO_CHAR / TO_TIMESTAMP statements.
Postgres FDW Setup Generator
Generate postgres_fdw CREATE SERVER, USER MAPPING and IMPORT FOREIGN SCHEMA SQL for querying a remote Postgres database.
Postgres EXCLUDE Constraint Generator
Generate PostgreSQL EXCLUDE constraint SQL: GiST/SP-GiST operators, btree_gist columns, partial WHERE and overlap-check verification.
pgvector Index & Schema Generator
Generate pgvector SQL: vector/halfvec columns, HNSW or IVFFlat indexes, tuned parameters and the matching nearest-neighbour query.
Postgres ALTER COLUMN TYPE Generator
Generate ALTER TABLE ALTER COLUMN TYPE SQL with the right USING cast, a table-rewrite verdict and a batched zero-downtime migration.
Postgres UPSERT Generator
Build INSERT ... ON CONFLICT DO UPDATE/DO NOTHING statements, the MERGE equivalent and the unique index they need.
pg_hba.conf Generator
Generate PostgreSQL client authentication rules with the right connection type, CIDR and auth method.
Postgres Trigger Generator
Generate CREATE TRIGGER SQL and plpgsql trigger functions: updated_at touch, JSONB audit log, operation guards and TG_OP skeletons.
Postgres VACUUM Command Generator
Build VACUUM / VACUUM FULL / ANALYZE commands with the right options, plus monitoring SQL and per-table autovacuum tuning.
SQL Pivot Generator (Rows to Columns)
Generate pivot queries with FILTER or CASE WHEN aggregates, the PostgreSQL crosstab() version and the reverse unpivot.
Epoch & Unix Timestamp Converter
Convert epoch to date and back with auto unit detection, plus to_timestamp and extract(epoch) SQL snippets.
pg_restore Command Generator
Build pg_restore or psql restore commands from a Postgres dump: archive format, parallel jobs, clean, no-owner and single-transaction options.
Postgres JSONB Query Builder
Generate JSONB queries from a nested path and operator, with the matching GIN or expression index and a JSONB cookbook.
SQL Schema Diff & Migration Generator
Compare two SQL schemas and generate the ALTER TABLE up and down migration, with lock and rewrite warnings.
Postgres Table Size Estimator
Estimate table and index size from your columns and row count, including tuple header, alignment padding and column-order savings.
Postgres Full Text Search Generator
Generate tsvector columns, GIN indexes, weighted ranking and ts_headline queries for PostgreSQL full text search.
Levenshtein Distance Calculator
Compute edit distance between two strings with the full DP matrix, edit path and matching Postgres fuzzy search SQL.
SQL Linter & Style Checker
Lint SQL for correctness traps, non-sargable predicates and style issues in your browser.
Database Normalization Analyzer
Find candidate keys and 1NF/2NF/3NF/BCNF violations, then get a lossless decomposition.
Connection Pool Size Calculator
Size your database connection pool from cores, latency and instances, with HikariCP, pgxpool, node-pg, SQLAlchemy and PgBouncer config.
PostgreSQL Error Code Lookup
Look up any SQLSTATE code or paste an error message to get the cause, the fix and how to catch it in your driver.
Postgres Autovacuum Calculator
Work out when autovacuum fires on a table, how much bloat builds up first, and generate per-table ALTER TABLE tuning.
SQL to MongoDB Query Converter
Convert a SQL SELECT into a MongoDB find() call or aggregation pipeline, with $lookup, $group, $match and $sort mapping.
pgloader Config Generator
Build a pgloader .load file to migrate MySQL, SQL Server, SQLite or CSV into PostgreSQL, with cast rules, table filters and verification SQL.
Postgres Upgrade Planner
Compare pg_upgrade, dump/restore and logical replication for a major version upgrade, with downtime estimates, commands and breaking changes.
SQL Join Visualizer
See INNER, LEFT, RIGHT, FULL, CROSS and anti joins run on real sample rows, with the SQL.
SCD Type 2 SQL Generator
Generate slowly changing dimension Type 2 DDL and load SQL for Postgres, Snowflake and BigQuery.
Postgres RLS Policy Generator
Generate PostgreSQL row level security policies for multi-tenant, per-user or role-based access.
Postgres Data Masking Generator
Build masked views, anonymization UPDATEs or PostgreSQL Anonymizer labels for sensitive columns.
Online SQL Playground
Run SQL in your browser against a sample SQLite database, with 10 checked practice exercises.
SQL CASE WHEN Generator
Build searched or simple CASE expressions with full queries and IF/IIF/DECODE equivalents per dialect.
SQL Set Operations Visualizer
See UNION, UNION ALL, INTERSECT and EXCEPT run on real rows, with counts and SQL per dialect.
Postgres Enum Type Generator
Generate CREATE TYPE, ADD VALUE, RENAME VALUE, safe value removal and enum-to-CHECK or lookup migrations.
Postgres Lock Conflict Checker
Check whether two PostgreSQL statements or LOCK TABLE modes block each other, with the conflict matrix and pg_locks queries.
Postgres Timezone Converter
Convert timestamps between IANA zones and generate AT TIME ZONE, SET timezone and date_trunc SQL with DST warnings.
Slow Query Log Analyzer
Group a MySQL or PostgreSQL slow query log by normalized query shape and rank the shapes by total time.
Postgres generate_series Builder
Build generate_series SQL for calendar tables, time buckets, gap-filled reports and test data, with a row preview.
Postgres Index Type Advisor
Pick between B-tree, Hash, GIN, GiST, SP-GiST, BRIN and HNSW for a column and query pattern, with the CREATE INDEX statement and operator class.
Postgres SERIAL to IDENTITY Converter
Convert a SERIAL or BIGSERIAL column to GENERATED AS IDENTITY with the correct setval, rollback and optional bigint widening.
Postgres DROP ROLE Helper
Generate the audit queries, REASSIGN OWNED, DROP OWNED and DROP ROLE script that clears "role cannot be dropped" errors.
pg_stat_statements Query Builder
Build version-correct Top-N pg_stat_statements queries by total time, mean time, calls, cache misses, temp spills or WAL.
AWS DMS Table Mapping Generator
Build a valid AWS DMS table-mappings.json with selection rules, schema and table renames, column removal and source row filters.
ClickHouse MergeTree Table Generator
Generate ClickHouse CREATE TABLE DDL with MergeTree engines, sorting keys, partitioning, TTL and compression codecs.
SQL Server to PostgreSQL Converter
Translate T-SQL DDL and queries to PostgreSQL: brackets, IDENTITY, NVARCHAR, TOP, GETDATE and more.
Docker Compose MySQL & MariaDB Generator
Generate docker-compose.yml for MySQL or MariaDB with volumes, healthchecks, init scripts and phpMyAdmin.
Oracle to PostgreSQL Converter
Translate Oracle DDL and SQL to PostgreSQL: VARCHAR2, NUMBER, NVL, DECODE, SYSDATE, sequences and more.
SQL Server Backup & Restore Command Generator
Generate T-SQL BACKUP and RESTORE scripts with compression, checksum, WITH MOVE, STOPAT and sqlcmd.
pgbench Command Generator
Build pgbench init and benchmark command lines for PostgreSQL load testing.
dbt schema.yml Generator
Turn a CREATE TABLE statement into a dbt schema.yml with data tests and a unit test skeleton.
DBML to SQL Converter
Convert DBML schemas to PostgreSQL or MySQL DDL, and turn existing CREATE TABLE statements back into DBML.
Liquibase Changelog Generator
Turn SQL DDL into a Liquibase changelog in XML, YAML, JSON or formatted SQL, with constraints and rollbacks.
MySQL Config Calculator
Generate a tuned my.cnf from your RAM, cores and workload, with an InnoDB memory budget check.
Debezium Connector Config Generator
Build a Debezium CDC connector config for PostgreSQL, MySQL, SQL Server, Oracle or MongoDB.
MongoDB Connection String Builder
Build or parse mongodb:// and mongodb+srv:// URIs with encoded passwords, auth and replica set options.
MySQL GRANT Statement Generator
Generate MySQL 8 CREATE USER, GRANT, role and REVOKE scripts for read-only, read-write or replication users.
SQL Server Connection String Builder
Build or parse SQL Server connection strings for ADO.NET, ODBC, JDBC, sqlcmd and SQLAlchemy with Encrypt options.
MySQL DATE_FORMAT Builder
Build MySQL DATE_FORMAT and STR_TO_DATE patterns with a live preview and every % format specifier explained.
Oracle tnsnames.ora Generator
Build or parse Oracle tnsnames.ora entries with RAC failover and TCPS, plus EZConnect, JDBC thin URLs and sqlplus.
SQL Server Date Format Converter
Every CONVERT date style code (101, 103, 112, 120, 126…) rendered live, plus a FORMAT() builder and string-to-date help.
SQL INSERT to CSV / JSON Converter
Turn INSERT statements or a mysqldump / pg_dump file into CSV, TSV, JSON or Markdown, with correct quoting and NULLs.
Oracle Date Format Builder
Live TO_CHAR preview for any Oracle date format mask (FM, TH/SP, IW, J, FF), common masks and TO_DATE string parsing.
SQL Parameter Binder
Paste a MyBatis or Hibernate log, or SQL with ?, $1 or :name placeholders, and get runnable SQL with the values filled in.
MySQL Error Code Lookup
Look up a MySQL error number, symbol or message and get the cause, a concrete fix and a code snippet to catch it in your driver.
SQL Data Dictionary Generator
Paste CREATE TABLE DDL and get a data dictionary with types, keys, defaults and comments as Markdown, HTML, CSV or JSON.
OtterMind
OtterMind