ALTER SEQUENCE RESTART WITH And CYCLE Bounds
Reset a PostgreSQL sequence with ALTER SEQUENCE RESTART vs RESTART WITH, inspect pg_sequences metadata, and toggle NO CYCLE to CYCLE wraparound.
Code
CREATE TEMP SEQUENCE batch_seq
START WITH 100
INCREMENT BY 10
MINVALUE 100
MAXVALUE 120
NO CYCLE;
SELECT nextval('batch_seq') AS v1, nextval('batch_seq') AS v2, nextval('batch_seq') AS v3;
-- With NO CYCLE, drawing past MAXVALUE raises an error instead of wrapping
DO $$
BEGIN
PERFORM nextval('batch_seq');
EXCEPTION
WHEN OTHERS THEN
RAISE NOTICE 'no-cycle stopped (%): %', SQLSTATE, SQLERRM;
END $$;
-- RESTART returns to START WITH (100); RESTART WITH N sets a custom next value
ALTER SEQUENCE batch_seq RESTART;
SELECT nextval('batch_seq') AS after_restart;
ALTER SEQUENCE batch_seq RESTART WITH 120 CYCLE;
SELECT nextval('batch_seq') AS at_max, nextval('batch_seq') AS wrapped_to_min;
SELECT start_value, min_value, max_value, increment_by, cycle, last_value
FROM pg_sequences
WHERE sequencename = 'batch_seq';Implementation trace — ALTER SEQUENCE RESTART WITH And CYCLE Bounds
The file runs SELECT / CREATE / ALTER statements, touching pg_sequences.
Concretely, the SQL combines: a WHERE clause that keeps only the rows a statement is meant to touch.
Using it
Run the statement against the pg_sequences table.
Key statements
SELECT start_value, min_value, max_value, increment_by, cycle, last_value
FROM pg_sequences
WHERE sequencename = 'batch_seq';
CREATE TEMP SEQUENCE batch_seq
START WITH 100
INCREMENT BY 10
MINVALUE 100
MAXVALUE 120
NO CYCLE;
SELECT nextval('batch_seq') AS v1, nextval('batch_seq') AS v2, nextval('batch_seq') AS v3;
Interactive Tools for This Topic
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- Which tables does this file reference?
- `pg_sequences`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.