Member-only story

Autoincrement ID Support in SQLAlchemy

Soumendra's Blog
2 min readMar 11, 2023

--

How to set primary key auto increment in sqlalchemy

Introduction

When working with a database, it is often necessary to create tables with unique identifiers for each row. One way to do this is by using autoincrement IDs. SQLAlchemy, a popular Python SQL toolkit, provides built-in support for autoincrement IDs. In this blog post, we’ll explore how to use autoincrement IDs in SQLAlchemy schema definitions and inserts.

Defining a Table with an Autoincrement ID

To define a table with an autoincrement ID in SQLAlchemy, we can use the Column class with the primary_key and autoincrement arguments. Here's an example:

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base


Base = declarative_base()

class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String)

In this example, we define a User table with an id column that is an Integer type, is the primary_key, and has autoincrement enabled. We also define a name column that is a String type.

Inserting Data with an Autoincrement ID

--

--

Soumendra's Blog
Soumendra's Blog

Written by Soumendra's Blog

AI Architect and Sustain Lead at PepsiCo

Responses (2)