Sitemap
Vengadesa Boopathi

Vengadesa Boopathi

SQLAlchemy and SQLModel

If you have been writing Python for a while and working with databases, you have probably heard of SQLAlchemy. And if you have been building APIs with FastAPI, you have likely run into SQLModel too. These two libraries are closely related, often confused, and absolutely worth understanding deeply.

This guide covers everything — from what these libraries actually are, to how they work under the hood, to building production-ready applications with them. No fluff, no skipping the important parts.

Part 1: Understanding the Problem These Libraries Solve

Before jumping into code, let us understand why these libraries even exist.

Back in the early days of Python web development, if you wanted to talk to a database, you had to use raw database drivers. Each database had its own driver with its own API. MySQL had MySQLdb, PostgreSQL had psycopg2, SQLite had the built-in sqlite3 module.

Here is what raw database execution looked like:

#sql
import sqlite3
conn = sqlite3.connect("mydb.db")
cursor = conn.cursor()
cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("Venki", "venki@example.com"))
conn.commit()
cursor.execute("SELECT * FROM users WHERE id = ?", (1,))
row = cursor.fetchone()
conn.close()

#postgresql
import psycopg2
conn = psycopg2.connect(host="localhost",database="mydb",user="postgres",password="password")
cursor = conn.cursor()
cursor.execute("INSERT INTO users (name, email) VALUES (%s, %s)",("Venki", "venki@example.com"))
conn.commit()
cursor.execute("SELECT * FROM users WHERE id = %s",(1,))
row = cursor.fetchone()
conn.close()

This works fine for a small script. But as your application grows, problems start appearing fast:

  • You are manually managing connections and cursors everywhere
  • If you switch from SQLite to PostgreSQL, you rewrite all your queries
  • No protection against SQL injection unless you are careful every single time
  • No way to represent database tables as Python objects
  • No connection pooling, so performance degrades under load

SQLAlchemy was created in 2006 by Michael Bayer specifically to solve all of these problems at once. It became the gold standard for database access in Python and has stayed that way for nearly two decades.

Part 2: What is SQLAlchemy

SQLAlchemy is a Python SQL toolkit and Object Relational Mapper. That definition sounds dry, so let us break it down into what it actually gives you.

A common interface for multiple databases. Write your code once and it works with PostgreSQL, MySQL, SQLite, Oracle, and MSSQL. You change one line — the connection string — and everything else stays the same.

Two layers to choose from. SQLAlchemy gives you a Core layer for writing SQL in a Pythonic way while staying close to raw SQL, and an ORM layer for working with Python classes and objects instead of SQL. You can use either or mix both in the same project.

Connection pooling out of the box. SQLAlchemy manages a pool of database connections so your app does not open and close a new connection for every single request. This is critical for any application with real traffic.

Protection against SQL injection by default. SQLAlchemy uses parameterized queries under the hood so you are safe without having to think about it.

Part 3: Installing SQLAlchemy

pip install sqlalchemy

For specific databases you also need the driver:

# PostgreSQL
pip install psycopg2-binary
# MySQL
pip install pymysql
# Async PostgreSQL
pip install asyncpg

SQLite needs no extra driver because it is built into Python.

Part 4: The Connection String

The connection string is how you tell SQLAlchemy which database to connect to. The format is:

dialect+driver://username:password@host:port/database

Real examples:

# SQLite (file based)
"sqlite:///myapp.db"
# SQLite (in memory, great for testing)
"sqlite:///:memory:"
# PostgreSQL
"postgresql://venki:password@localhost:5432/mydb"
# PostgreSQL with asyncpg (async)
"postgresql+asyncpg://venki:password@localhost:5432/mydb"
# MySQL
"mysql+pymysql://venki:password@localhost:3306/mydb"

Part 5: The Engine — Your Entry Point to Everything

The engine is the starting point of any SQLAlchemy application. It holds the connection pool and knows how to talk to your specific database.

from sqlalchemy import create_engine

engine = create_engine("sqlite:///myapp.db")

The engine does not actually connect to the database when you create it. It connects lazily when you first need it.

You can configure the connection pool:

engine = create_engine(
"postgresql://venki:password@localhost/mydb",
pool_size=10, # number of connections to keep open
max_overflow=20, # extra connections allowed beyond pool_size
pool_timeout=30, # seconds to wait before giving up
pool_recycle=1800, # recycle connections after 30 minutes
echo=True # log all SQL statements (great for debugging)
)

Part 6: SQLAlchemy Core — Writing SQL the Pythonic Way

The Core layer lets you write SQL using Python constructs while staying close to actual SQL. This is useful when you need full control over your queries.

Running Raw SQL with text()

In SQLAlchemy 2.x, all raw SQL strings must be wrapped in text():

from sqlalchemy import create_engine, text
engine = create_engine("sqlite:///myapp.db")

with engine.connect() as conn:
result = conn.execute(text("SELECT * FROM users"))
for row in result:
print(row)

Always use named parameters with :param syntax, never f-strings:

# WRONG — SQL injection risk
name = "Venki"
conn.execute(text(f"SELECT * FROM users WHERE name = '{name}'"))

# RIGHT - safe parameterized query
conn.execute(text("SELECT * FROM users WHERE name = :name"), {"name": name})

Creating Tables with Core

from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData

engine = create_engine("sqlite:///myapp.db")
metadata = MetaData()
users = Table(
"users",
metadata,
Column("id", Integer, primary_key=True),
Column("name", String(100), nullable=False),
Column("email", String(200), unique=True),
)
metadata.create_all(engine)

Insert, Select, Update, Delete with Core

from sqlalchemy import insert, select, update, delete

# Insert
with engine.connect() as conn:
conn.execute(insert(users).values(name="Venki", email="venki@example.com"))
conn.commit()
# Select
with engine.connect() as conn:
result = conn.execute(select(users).where(users.c.name == "Venki"))
for row in result:
print(row)
# Update
with engine.connect() as conn:
conn.execute(update(users).where(users.c.id == 1).values(name="Venkatesh"))
conn.commit()
# Delete
with engine.connect() as conn:
conn.execute(delete(users).where(users.c.id == 1))
conn.commit()

Part 7: The ORM Layer — Working With Python Classes

The ORM (Object Relational Mapper) layer is where SQLAlchemy really shines. Instead of writing SQL, you define Python classes that map to database tables and SQLAlchemy handles the SQL for you.

Defining Models

In SQLAlchemy 2.x, the recommended way uses DeclarativeBase:

from sqlalchemy import String, Integer
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

class Base(DeclarativeBase):
pass
class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
name: Mapped[str] = mapped_column(String(100), nullable=False)
email: Mapped[str] = mapped_column(String(200), unique=True)
def __repr__(self):
return f"User(id={self.id}, name={self.name})"

The Mapped annotation is new in SQLAlchemy 2.x and gives you proper type checking. The old 1.x style still works but the new style is recommended for new projects.

Creating Tables From Models

from sqlalchemy import create_engine

engine = create_engine("sqlite:///myapp.db", echo=True)
Base.metadata.create_all(engine)

Sessions — The Core of ORM Operations

A session is the main way you interact with the database through the ORM. Think of it as a staging area. You add objects to it, and when you commit, they get written to the database.

from sqlalchemy.orm import Session
# Create
with Session(engine) as session:
user = User(name="Venki", email="venki@example.com")
session.add(user)
session.commit()
session.refresh(user) # reload to get auto-generated id
print(user.id)
# Read
with Session(engine) as session:
user = session.get(User, 1) # get by primary key
print(user.name)
# Read with filter
from sqlalchemy import select
with Session(engine) as session:
stmt = select(User).where(User.name == "Venki")
users = session.execute(stmt).scalars().all()
# Update
with Session(engine) as session:
user = session.get(User, 1)
user.name = "Venkatesh"
session.commit()
# Delete
with Session(engine) as session:
user = session.get(User, 1)
session.delete(user)
session.commit()

Part 8: Relationships Between Tables

Real applications always have tables that relate to each other. SQLAlchemy handles this beautifully.

One to Many

One user has many posts. Each post belongs to one user.

from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship

class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(100))
posts: Mapped[list["Post"]] = relationship("Post", back_populates="user")
class Post(Base):
__tablename__ = "posts"
id: Mapped[int] = mapped_column(primary_key=True)
title: Mapped[str] = mapped_column(String(200))
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"))
user: Mapped["User"] = relationship("User", back_populates="posts")

Using the relationship:

with Session(engine) as session:
user = User(name="Venki")
post1 = Post(title="SQLAlchemy Guide", user=user)
post2 = Post(title="FastAPI Tutorial", user=user)
    session.add(user)
session.commit()
# Access posts through the relationship
user = session.get(User, 1)
for post in user.posts:
print(post.title)

Many to Many

Students can enroll in many courses. Courses can have many students.

from sqlalchemy import Table
enrollment = Table(
"enrollment",
Base.metadata,
Column("student_id", ForeignKey("students.id"), primary_key=True),
Column("course_id", ForeignKey("courses.id"), primary_key=True),
)
class Student(Base):
__tablename__ = "students"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(100))
courses: Mapped[list["Course"]] = relationship("Course", secondary=enrollment, back_populates="students")
class Course(Base):
__tablename__ = "courses"
id: Mapped[int] = mapped_column(primary_key=True)
title: Mapped[str] = mapped_column(String(200))
students: Mapped[list["Student"]] = relationship("Student", secondary=enrollment, back_populates="courses")

Part 9: Lazy vs Eager Loading

This is one of the most important performance topics in SQLAlchemy.

Lazy loading (the default) means related objects are fetched only when you actually access them. This causes the N+1 problem — one query for the main objects, then one more query per object to fetch related data.

# This triggers N+1 queries
users = session.execute(select(User)).scalars().all()
for user in users:
print(user.posts) # a new query fires for EACH user

Eager loading fetches everything in one query using a JOIN.

from sqlalchemy.orm import joinedload
# One query fetches users AND their posts
users = session.execute(
select(User).options(joinedload(User.posts))
).scalars().unique().all()
for user in users:
print(user.posts) # no extra queries

Always use eager loading when you know you will access related data.

Part 10: Transactions

SQLAlchemy gives you full control over transactions.

with Session(engine) as session:
try:
user = User(name="Venki", email="venki@example.com")
session.add(user)

post = Post(title="First Post", user=user)
session.add(post)
session.commit() # both saved together
except Exception as e:
session.rollback() # neither saved if anything fails
raise e

The with statement automatically rolls back if an exception escapes.

Part 11: Async SQLAlchemy

Modern web frameworks like FastAPI are async. SQLAlchemy 2.0 added full async support.

from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
engine = create_async_engine(
"postgresql+asyncpg://venki:password@localhost/mydb",
echo=True
)
AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False)
async def get_user(user_id: int):
async with AsyncSessionLocal() as session:
user = await session.get(User, user_id)
return user
async def create_user(name: str, email: str):
async with AsyncSessionLocal() as session:
user = User(name=name, email=email)
session.add(user)
await session.commit()
await session.refresh(user)
return user

Part 12: Database Migrations with Alembic

SQLAlchemy creates tables but it does not handle schema changes. If you add a column to your model, SQLAlchemy will not automatically add it to your existing database. That is Alembic’s job.

Get Vengadesa Boopathi’s stories in your inbox

Join Medium for free to get updates from this writer.

Alembic is the official migration tool for SQLAlchemy.

pip install alembic
alembic init migrations

Configure alembic.ini with your database URL, then edit migrations/env.py to import your models.

Create a migration after changing your models:

alembic revision --autogenerate -m "add phone column to users"

Apply the migration:

alembic upgrade head

Roll back the last migration:

alembic downgrade -1

In production, always run alembic upgrade head as part of your deployment process.

Part 13: Using Pandas With SQLAlchemy

SQLAlchemy integrates nicely with Pandas for data analysis work.

import pandas as pd
from sqlalchemy import create_engine, text
engine = create_engine("sqlite:///myapp.db")# Read query result into DataFrame
df = pd.read_sql(text("SELECT * FROM users"), engine)
# Write DataFrame to database
df.to_sql("new_table", engine, if_exists="replace", index=False)

Part 14: SQLAlchemy 1.x vs 2.x — What Changed

If you are reading old tutorials, you will see code like this:

# Old 1.x style
session.query(User).filter(User.name == "Venki").all()
session.query(User).filter_by(name="Venki").first()

In 2.x the recommended style is:

# New 2.x style
session.execute(select(User).where(User.name == "Venki")).scalars().all()
session.execute(select(User).where(User.name == "Venki")).scalar_one_or_none()

The old style still works in 2.x but will eventually be removed. Start new projects with the 2.x style.

Part 15: What is SQLModel

SQLModel is a library built on top of SQLAlchemy and Pydantic by Tiangolo, the creator of FastAPI. It was released in 2021 to solve a specific pain point that every FastAPI developer feels.

In FastAPI, you need two separate class definitions for the same data:

  1. A SQLAlchemy model for the database layer
  2. A Pydantic model for request and response validation

This means you write essentially the same fields twice and keep them in sync manually. With a simple User table you might have UserDB, UserCreate, UserRead, UserUpdate — four different classes all representing the same thing.

SQLModel merges Pydantic and SQLAlchemy into a single class definition.

Part 16: Installing SQLModel

pip install sqlmodel

SQLModel automatically installs compatible versions of SQLAlchemy and Pydantic.

Part 17: Defining Models With SQLModel

from sqlmodel import SQLModel, Field
class User(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str
email: str

The table=True argument tells SQLModel this class maps to a real database table. Without it, the class is just a Pydantic model for validation.

This one class does the work of both a SQLAlchemy model and a Pydantic model. You can use it for database operations and also use it to validate API request bodies.

Part 18: Creating Tables and Session With SQLModel

from sqlmodel import create_engine, Session, SQLModel
engine = create_engine("sqlite:///myapp.db", echo=True)SQLModel.metadata.create_all(engine)

Session works the same as SQLAlchemy session:

with Session(engine) as session:
user = User(name="Venki", email="venki@example.com")
session.add(user)
session.commit()
session.refresh(user)
print(user.id)

Part 19: Multiple Models for the Same Table

This is where SQLModel really shines. You can define multiple Pydantic-only models (without table=True) that share fields with your table model.

from sqlmodel import SQLModel, Field
# Base model with shared fields (not a table)
class UserBase(SQLModel):
name: str
email: str
# Table model (actual database table)
class User(UserBase, table=True):
id: int | None = Field(default=None, primary_key=True)
hashed_password: str # stored in DB but never returned to user
# What the API accepts when creating a user
class UserCreate(UserBase):
password: str # plain password, only used during creation
# What the API returns (no password at all)
class UserRead(UserBase):
id: int
# What the API accepts when updating a user
class UserUpdate(SQLModel):
name: str | None = None
email: str | None = None

This pattern gives you clean separation between what goes in the database and what you expose through your API.

Part 20: SQLModel With FastAPI — A Complete Example

Here is a complete working FastAPI application with SQLModel:

from fastapi import FastAPI, HTTPException, Depends
from sqlmodel import SQLModel, Field, Session, create_engine, select
from typing import Generator

# Models
class UserBase(SQLModel):
name: str
email: str
class User(UserBase, table=True):
id: int | None = Field(default=None, primary_key=True)
class UserCreate(UserBase):
pass
class UserRead(UserBase):
id: int
# Database setup
DATABASE_URL = "sqlite:///./myapp.db"
engine = create_engine(DATABASE_URL, echo=True)
def create_db():
SQLModel.metadata.create_all(engine)
def get_session() -> Generator:
with Session(engine) as session:
yield session
# App
app = FastAPI()
@app.on_event("startup")
def on_startup():
create_db()
@app.post("/users/", response_model=UserRead)
def create_user(user: UserCreate, session: Session = Depends(get_session)):
db_user = User.model_validate(user)
session.add(db_user)
session.commit()
session.refresh(db_user)
return db_user
@app.get("/users/{user_id}", response_model=UserRead)
def get_user(user_id: int, session: Session = Depends(get_session)):
user = session.get(User, user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
@app.get("/users/", response_model=list[UserRead])
def list_users(session: Session = Depends(get_session)):
users = session.execute(select(User)).scalars().all()
return users
@app.patch("/users/{user_id}", response_model=UserRead)
def update_user(user_id: int, user_data: dict, session: Session = Depends(get_session)):
user = session.get(User, user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
for key, value in user_data.items():
setattr(user, key, value)
session.commit()
session.refresh(user)
return user
@app.delete("/users/{user_id}")
def delete_user(user_id: int, session: Session = Depends(get_session)):
user = session.get(User, user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
session.delete(user)
session.commit()
return {"message": "User deleted"}

Part 21: Relationships in SQLModel

from sqlmodel import SQLModel, Field, Relationship
from typing import Optional

class User(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str
posts: list["Post"] = Relationship(back_populates="user")
class Post(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
title: str
user_id: int | None = Field(default=None, foreign_key="user.id")
user: User | None = Relationship(back_populates="posts")

Note that SQLModel uses Relationship instead of SQLAlchemy's relationship.

Part 22: Async With SQLModel

SQLModel supports async the same way SQLAlchemy does:

from sqlmodel.ext.asyncio.session import AsyncSession
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker

engine = create_async_engine("postgresql+asyncpg://venki:password@localhost/mydb")
AsyncSessionLocal = async_sessionmaker(engine, class_=AsyncSession)
async def get_user(user_id: int):
async with AsyncSessionLocal() as session:
user = await session.get(User, user_id)
return user

Part 23: SQLAlchemy vs SQLModel — When to Use Which

Use SQLAlchemy when:

  • You are not using FastAPI
  • You need maximum control and flexibility over your database layer
  • You have complex queries with multiple joins and aggregations
  • You need battle tested stability that has been proven in production for 15+ years
  • You are working on an existing codebase that already uses SQLAlchemy

Use SQLModel when:

  • You are building a FastAPI application
  • You want to write less code and maintain fewer class definitions
  • Your team is comfortable with Pydantic and wants unified models
  • You are starting a new project and want the cleanest possible code structure

The important thing to understand: SQLModel is SQLAlchemy under the hood. Everything you know about SQLAlchemy — sessions, queries, relationships, migrations with Alembic — applies to SQLModel too. You are not choosing between them, you are choosing how much abstraction you want on top of SQLAlchemy.

Part 24: Production Checklist

Before shipping a SQLAlchemy or SQLModel application to production, make sure you have covered these:

Connection pooling configured — set pool_size, max_overflow, and pool_recycle appropriate for your expected traffic.

Environment variables for credentials — never hardcode database URLs. Use environment variables or a secrets manager.

import os
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./dev.db")

Alembic migrations set up — never use create_all() in production to manage schema. Use Alembic so you have a history of changes and can roll back safely.

Connection error handling — wrap database operations in try/except and handle connection failures gracefully.

Async for FastAPI — if you are using FastAPI, use the async versions of the engine and session to get the full performance benefit.

Index your columns — add database indexes to columns you filter or sort by frequently.

class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(primary_key=True)
email: Mapped[str] = mapped_column(String(200), index=True) # indexed

Close sessions properly — always use context managers or dependency injection to ensure sessions are closed after each request.

Wrapping Up

SQLAlchemy is one of those libraries that pays dividends the more you invest in learning it. It has been the backbone of Python database access for nearly two decades for good reason. It is mature, flexible, and does not get in your way when you need to drop down to raw SQL.

SQLModel is the natural evolution for FastAPI developers who got tired of the boilerplate. It gives you the power of SQLAlchemy with significantly less ceremony.

The best way to learn either of them is to build something real. Start with SQLite since it needs zero setup, get your models working, then swap the connection string to PostgreSQL when you are ready for production. That single line change is one of the best demonstrations of why using an ORM layer is worth it.