How to set auto increment primary key in PostgreSQL?
To set an auto-increment primary key in PostgreSQL, use the SERIAL
or BIGSERIAL
data type. This type will auto-create and auto-increment a SEQUENCE
.
For instance:
If you prefer setting up a custom sequence, do the following:
Remember to use BIGSERIAL
/BIGINT
for larger tables.
Advanced Auto-Increment Handling
Auto-increment for existing tables
Say you're on a boat and forgot to set your auto-incrementing primary key before sailing. Don't panic! Use the ALTER TABLE
:
It will take care of creating the SEQUENCE
and setting the default value for you.
Sequence Ownership Management
To remove any confusions in your RDBMS family, match ownership between SEQUENCE
and their pertaining tables:
Catering to atypical increment patterns
Your table may require a custom increment value or a different start value. That's no issue:
Don't forget to update your sequence if you've skipped the starting gun and already populated the table:
Transitioning to IDENTITY:
For PostgreSQL 10+ fans, you can switch from SERIAL
with this stage dive:
Additional tips, tricks and traps in Auto-Increment
Overcoming COPY command obstacle
Battling duplicate keys after a COPY
command? Try this super-hero move:
Maximizing efficiency with INSERT INTO
Leverage auto-increments for performance with this swift move:
Maintaining data integrity
For manual sequence management, take control and ensure UNIQUE NOT NULL
:
Was this article helpful?