How to Define an Auto Increment Primary Key in PostgreSQL using Python?
Last Updated :
06 Jan, 2023
Prerequisite: PostgreSQL
Python has various database drivers for PostgreSQL. Currently, most used version is psycopg2 because it fully implements the Python DB-API 2.0 specification. The psycopg2 provides many useful features such as client-side and server-side cursors, asynchronous notification and communication, COPY command support, etc.
Installation
psycopg2 can be downloaded like any other module using the following command:
pip install psycopg2
Approach
PostgreSQL's way of creating Primary key with auto increment feature :
A column has to be defined with SERIAL PRIMARY KEY. Here SERIAL is not a true data type, but is simply shorthand notation that tells Postgres to create an auto incremented, unique identifier for the specified column. By simply setting a column as SERIAL with PRIMARY KEY attached, Postgres will handle all the complicated behind-the-scenes work and automatically increment our the specified column with a unique, primary key value for every INSERT.
Database Information
Database name: testdb
Table name: EMPLOYEE
In the EMPLOYEE TABLE, column named EMPLOYEE_ID will be implemented as an auto-incremented Primary key column.
Syntax:
CREATE TABLE <table_name>(
<column1_name> SERIAL NOT NULL PRIMARY KEY,
.
.
);
The implementation of creating a table with such specification is given below:
Python3
import psycopg2
def create_table():
conn = None
try:
# connect to the PostgreSQL server
conn = psycopg2.connect(database="testdb", user="postgres",
password="password", host="127.0.0.1", port="5432")
print("Opened database successfully")
# create a cursor
cursor = conn.cursor()
# Dropping EMPLOYEE table if already exists.
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
# Creating table as per requirement, let us have EMPLOYEE table
# and in order to have auto increment primary key, EMPLOYEE_ID SERIAL PRIMARY KEY
# is used and it is explained before code
sql = '''CREATE TABLE EMPLOYEE(
EMPLOYEE_ID SERIAL PRIMARY KEY,
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT
)'''
cursor.execute(sql)
print("Table created successfully........")
# close communication with the PostgreSQL database server
cursor.close()
# commit the changes
conn.commit()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
if __name__ == '__main__':
create_table()
We can see the table created using pgadmin tool

Now, Insertion needs to done to see if our auto-increment feature works or not. This can be done either directly through pgadmin or using python code.
pgadmin way :
Below is the screenshot that shows execution of insert queries and resultant result-set.
Explanation of auto increment primary key
Using python code:
Python3
import psycopg2
try:
connection = psycopg2.connect(user="postgres",
password="password",
host="127.0.0.1",
port="5432",
database="testdb")
cursor = connection.cursor()
# As Employee table is having auto incremented primary id column(employee_id), no need to specify about that value here
postgres_insert_query = ''' INSERT INTO EMPLOYEE (FIRST_NAME, LAST_NAME, AGE,SEX,INCOME) VALUES (%s,%s,%s,%s,%s)'''
record_to_insert = ('asd', 'wer', 19, 'f', 5000)
cursor.execute(postgres_insert_query, record_to_insert)
connection.commit()
count = cursor.rowcount
print(count, "Record inserted successfully into Employee table")
except (Exception, psycopg2.Error) as error:
if(connection):
print("Failed to insert record into Employee table", error)
finally:
# closing database connection.
if(connection):
cursor.close()
connection.close()
print("PostgreSQL connection is closed")
Output of employee table after executing above program :

Similar Reads
How to Copy a Table Definition in MySQL Using Python? Python requires an interface to access a database server. Python supports a wide range of interfaces to interact with various databases. To communicate with a MySQL database, MySQL Connector Python module, an API written purely in Python, is used. This module is self-sufficient meaning that it does
6 min read
How to import and export data using CSV files in PostgreSQL In this article, we are going to see how to import and export data using CSV file in PostgreSQL, the data in CSV files can be easily imported and exported using PostgreSQL. To create a CSV file, open any text editor (notepad, vim, atom). Write the column names in the first line. Add row values separ
3 min read
Python PostgreSQL - Transaction management using Commit and Rollback In this article, we are going to see how to transaction management using Commit and Rollback. In pyscopg, the connection class in psycopg is in charge of processing transactions. When you use a cursor object to issue your first SQL statement to the PostgreSQL database, psycopg generates a new trans
4 min read
Do loop in Postgresql Using Psycopg2 Python In this article, we use psycopg2 to loop through all data points using psycopg2 function in Python. We will first connect our PostgreSQL database using psycopg2.connect method, and pass the connection parameters such as the host, database, user, and password. Then we will create a cursor using the c
4 min read
PostgreSQL - Create table using Python Creating tables in a PostgreSQL database using Python is a common task for developers working with databases. This process involves defining the structure of your data and ensuring that your database is optimized for efficient storage and retrieval. In this article, we will walk through the steps of
3 min read
PostgreSQL - Connecting to the Database using Python PostgreSQL in Python offers a robust solution for developers looking to interact with databases seamlessly. With the psycopg2 tutorial, we can easily connect Python to PostgreSQL, enabling us to perform various database operations efficiently. In this article, we will walk you through the essential
4 min read