Alter data type of a column to serial
Here's the candy you're looking for — transforming a column to serial
type using a sequence
in PostgreSQL:
It magically morphs your humble your_table.your_column
into a strapping SERIAL
column.
Unveiling PostgreSQL serial
Inside PostgreSQL, SERIAL
is not a standalone guardian, but more like a shortcut that says "hey, let's make this integer column special with an auto-incrementing capability".
When you give birth to a new table, declaring a column SERIAL
makes PostgreSQL busy — automatically creating a sequence that injects life into it, making it grow by itself with each new entry.
However, when an existing column undergoes puberty, you can't just miraculously alter it to SERIAL
. You need a more explicit series of spells that involve creating a sequence, setting next value, and linking it. Voila!
A quick heads-up
Our beautiful PostgreSQL world is not without its quirks and gotchas:
- Conduct the
setval
ritual after inserting the sequence to ensure it starts from your preferred base camp. - Deleting a column or table? Make sure to clean up your sequences as well, else they might turn into orphaned zombies.
OWNED BY
to the rescue! - Always be nice to concurrency — when modifying sequences, ensure proper locking to avoid collisions.
More magic potions
Assigning sequence ownership
Using bigserial
For a giant range use bigserial
:
Reincarnating a sequence
To restart a sequence from a new birth:
Advanced sequence maneuvering
Serial or sequence
Choosing between SERIAL
and creating a custom sequence boils down to your specific needs. If you require controlled increments, tables sharing a sequence, or non-standard increments, use CREATE SEQUENCE
.
Crafting custom sequence
A handful of neat options are available with CREATE SEQUENCE
such as INCREMENT BY
, MINVALUE
, and MAXVALUE
:
Sharing sequences
Sharing is caring! For a shared counter between tables, use a common sequence:
Sequence alignment
A periodic re-checking of the sequence health is crucial. Sequences may disarrange over time - with scripts forgetting or ignoring to use them, leading to erratic gaps or overlaps.
Was this article helpful?