Skip to content

Instantly share code, notes, and snippets.

@slavamokerov
Last active July 9, 2025 14:35
Show Gist options
  • Save slavamokerov/7f98be752297856109d322d2916f9ee4 to your computer and use it in GitHub Desktop.
Save slavamokerov/7f98be752297856109d322d2916f9ee4 to your computer and use it in GitHub Desktop.
Creating sequence in an existing table. PostgreSQL
/*
objects_id_object_seq - sequence name
objects - table name
id_object - ID field name
seq - standard postfix
Doc for setval() and nextval(): https://www.postgresql.org/docs/current/functions-sequence.html
*/
CREATE SEQUENCE IF NOT EXISTS objects_id_object_seq; -- IF NOT EXISTS is works only in Postgres 9.5+
SELECT setval(
'objects_id_object_seq',
(SELECT max(id_object) FROM objects)
);
ALTER TABLE objects ALTER COLUMN id_object SET DEFAULT nextval('objects_id_object_seq');
@fleal07
Copy link

fleal07 commented Jul 26, 2021

Nice, Very Good

@JanHron
Copy link

JanHron commented Feb 5, 2022

Is there a reason for the increment in the maximum value of id_object? Wouldn't SELECT setval('objects_id_object_seq', (SELECT max(id_object) FROM objects)); do the same thing while being simpler and omitting the false value?

@slavamokerov
Copy link
Author

slavamokerov commented Feb 5, 2022

Is there a reason for the increment in the maximum value

You're right, there's no reason. Fixed.

@walkermatt
Copy link

Also consider associating the sequence with the table column:

ALTER SEQUENCE IF EXISTS objects_id_object_seq OWNED BY objects_id_object_seq.id_object;

See OWNED BY table_name.column_name for details.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment