Lesson 16 of 59Data and storage
Databases with SQLAlchemy
Model tables and relations, write safe SQL, use SQLAlchemy 2.0 sessions in FastAPI, and avoid N+1 queries.
So far your todos live in a Python list and vanish on every restart. Real apps keep data in a database, and almost every backend job involves one: designing tables, writing queries, keeping writes consistent, and finding the slow query when a page takes four seconds. This lesson covers the relational basics, real SQL you can run right here, and how FastAPI apps talk to a database through SQLAlchemy.
Tables, keys and relations
A relational database (PostgreSQL, MySQL, SQLite) stores data in tables. Each table has fixed columns with types, and each record is a row.
- A primary key uniquely identifies a row, usually an auto-incrementing
id. - A foreign key is a column that points at another table's primary key.
todos.user_idpointing atusers.idsays "this todo belongs to that user". The database refuses auser_idthat does not exist. - That is a one-to-many relation: one user, many todos. Many-to-many (todos and tags) needs a third table of pairs, like
todo_tags(todo_id, tag_id). - A unique constraint (say on
users.email) makes the database reject duplicates, even if two requests race. Your API turns that error into a409.
The todos table. The user_id column is a foreign key into users, where user 1 is Ada and user 2 is Sam.
SQL you can run
SQL is the language you use to ask a relational database for data. SQLite ships inside Python as the sqlite3 module, so you can run real SQL right here, in memory.
Press Run (⌘ Enter) to see what happens.JOIN keeps only rows that match on both sides. LEFT JOIN keeps every row from the left table even when nothing matches (a user with zero todos still appears, with a count of 0). GROUP BY folds rows into one per group so COUNT can count them.
Using the same tables, what does this print?
print(db.execute("SELECT COUNT(*) FROM todos WHERE user_id = 2 AND done = 0").fetchone()[0])Never build SQL with f-strings
The single most dangerous database mistake is pasting user input into a query string. That is SQL injection, and it still tops security reports.
Press Run (⌘ Enter) to see what happens.The f-string version returns every user's todos, because the input rewrote the WHERE clause. With a ? placeholder the driver sends the value separately from the SQL, so it can only ever be data. SQLAlchemy always uses parameters for you, which is one good reason to use it.
SQLAlchemy 2.0: tables as classes
SQLAlchemy is Python's standard database toolkit. Its ORM (object relational mapper) lets you describe tables as classes and work with rows as objects. Version 2.0 uses type hints throughout:
from sqlalchemy import ForeignKey, String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
class Base(DeclarativeBase):
pass
class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(primary_key=True)
email: Mapped[str] = mapped_column(String(255), unique=True, index=True)
todos: Mapped[list["Todo"]] = relationship(back_populates="owner")
class Todo(Base):
__tablename__ = "todos"
id: Mapped[int] = mapped_column(primary_key=True)
title: Mapped[str] = mapped_column(String(200))
done: Mapped[bool] = mapped_column(default=False)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
owner: Mapped[User] = relationship(back_populates="todos")Mapped[int] declares the Python type; mapped_column adds database details. Mapped[str | None] would make the column nullable. relationship gives you user.todos and todo.owner as Python attributes, built from the foreign key.
Queries use select(), which reads a lot like SQL:
from sqlalchemy import select
from sqlalchemy.orm import Session
from app.models import Todo
def list_open_todos(db: Session, user_id: int, limit: int = 20) -> list[Todo]:
stmt = (
select(Todo)
.where(Todo.user_id == user_id, Todo.done.is_(False))
.order_by(Todo.id)
.limit(limit)
)
return list(db.scalars(stmt))
def create_todo(db: Session, user_id: int, title: str) -> Todo:
todo = Todo(title=title, user_id=user_id)
db.add(todo)
db.flush() # sends the INSERT now, so todo.id is filled in
return tododb.get(Todo, 42) fetches by primary key. db.scalars(stmt) runs a query and yields model objects; db.execute(stmt) yields rows when you select several columns.
Match each SQLAlchemy piece to its job.
Sessions and transactions
A transaction groups several statements so they all succeed or all fail. Moving money from one account to another is two UPDATEs; if the server crashes between them, the transaction guarantees neither happened. A session in SQLAlchemy collects your changes and sends them inside one transaction when you call commit(), or throws them away on rollback().
In FastAPI the rule is one session per request, created and closed by a yield dependency (exactly the get_db you saw in Dependency Injection):
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
engine = create_engine("postgresql+psycopg://app:secret@localhost:5432/todos", pool_pre_ping=True)
SessionLocal = sessionmaker(bind=engine, expire_on_commit=False)
def get_db():
with SessionLocal() as db:
with db.begin(): # commits on success, rolls back on exception
yield dbThe dependency opens a session. It borrows a connection from the engine's pool, which is much faster than opening a new one.
Async SQLAlchemy and SQLModel
For async def routes, SQLAlchemy has an async API: create_async_engine("postgresql+asyncpg://..."), AsyncSession, and await db.scalars(stmt). The models stay the same. Install it with uv add "sqlalchemy[asyncio]" asyncpg: since SQLAlchemy 2.1 the greenlet package that the async layer needs is no longer installed by default, so the asyncio extra is required. Async Databases: SQLAlchemy AsyncSession, asyncpg and SQLModel covers the async API, MissingGreenlet and pool sizing in depth.
SQLModel, by FastAPI's author, combines a Pydantic model and a SQLAlchemy model in one class, so the same Todo can be a table and a response schema. It is pleasant for small apps; many teams still keep separate SQLAlchemy models and Pydantic schemas so the API shape and the table shape can change independently.
Migrations with Alembic
Your tables will change: a new due_date column, a renamed field. You cannot just drop and recreate a production database, so you write migrations: small versioned scripts that change the schema step by step. Alembic is SQLAlchemy's migration tool.
uv add alembicalembic init alembic # creates alembic/ and alembic.inialembic revision --autogenerate -m "add due_date" # compares models to the DB, writes a scriptalembic upgrade head # applies every migration not yet runalembic downgrade -1 # undoes the last oneAutogenerate compares your models with the live database and writes the op.add_column(...) calls for you. Always read the generated file before committing it: a rename can show up as "drop column, add column", which deletes data. The next lesson, Database Migrations with Alembic, covers the full workflow.
Order the steps to add a due_date column in production.
- Tap the steps below in the right order.
N+1 queries and indexes
The most common ORM performance bug is the N+1 query: one query for a list, then one more per item.
Press Run (⌘ Enter) to see what happens.With the ORM it hides inside innocent code: for todo in todos: print(todo.owner.email) lazily loads each owner. The fix is to load relations up front with select(Todo).options(selectinload(Todo.owner)) (one extra query for all owners) or joinedload (a JOIN).
The last two lines show an index. Without it, SQLite must SCAN the whole table to find user_id = 7. With it, it can SEARCH using the index, like a book index instead of reading every page. Index the columns you filter, join or sort on (foreign keys especially). Each index slows writes a little and takes space, so do not index everything. In PostgreSQL, EXPLAIN ANALYZE shows the real plan and timings.
Practice
Top authors with SQL
Practice real SQL with the built-in sqlite3 module. Write top_authors(users, posts, min_posts):
usersis a list of[id, name],postsa list of[id, user_id, title].- Load them into an in-memory SQLite database (
sqlite3.connect(":memory:")), using?placeholders for every insert. - Return
[[name, post_count], ...]for users with at leastmin_postsposts, ordered bypost_countdescending, thennameascending.
Users with no posts count as 0, so with min_posts = 0 every user appears (this needs a LEFT JOIN).
users = [[1, "Ada"], [2, "Sam"], [3, "Leo"]]
posts = [[1, 1, "a"], [2, 1, "b"], [3, 2, "c"]]
top_authors(users, posts, 1) -> [["Ada", 2], ["Sam", 1]]
top_authors(users, posts, 0) -> [["Ada", 2], ["Sam", 1], ["Leo", 0]]- foreign key
- A column holding another table's primary key, like
todos.user_id. The database rejects ids that do not exist. - transaction
- A group of statements that all commit or all roll back together.
- Session
- SQLAlchemy's unit of work. One per request, created and closed by a yield dependency.
- migration
- A versioned script that changes the schema, managed with Alembic (
alembic upgrade head). - N+1 query
- One query for a list plus one per item. Fixed with a JOIN or eager loading like
selectinload. - index
- A lookup structure that lets the database find rows without scanning the table. Speeds reads, slightly slows writes.