Skip to content

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.

21 min read0/6 questions

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_id pointing at users.id says "this todo belongs to that user". The database refuses a user_id that 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 a 409.
A foreign key connects two tables
idtitledoneuser_id
todo 11Buy milk01
todo 22Write tests12
todo 33Walk dog01
todo 44Ship v202

The todos table. The user_id column is a foreign key into users, where user 1 is Ada and user 2 is Sam.

1/3
Quick check
Where does the foreign key go for "a user has many todos"?
Need a nudge? A hint rules out a wrong answer.

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.

Pythonsql_basics.py
import sqlite3 db = sqlite3.connect(":memory:")db.executescript("""CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE);CREATE TABLE todos ( id INTEGER PRIMARY KEY, title TEXT NOT NULL, done INTEGER NOT NULL DEFAULT 0, user_id INTEGER NOT NULL REFERENCES users(id));INSERT INTO users (name) VALUES ('Ada'), ('Sam');INSERT INTO todos (title, done, user_id) VALUES ('Buy milk', 0, 1), ('Write tests', 1, 2), ('Walk dog', 0, 1), ('Ship v2', 0, 2);""") print(db.execute("SELECT id, title FROM todos WHERE done = 0 ORDER BY id").fetchall()) print(db.execute(""" SELECT users.name, todos.title FROM todos JOIN users ON users.id = todos.user_id WHERE todos.done = 0""").fetchall()) print(db.execute(""" SELECT users.name, COUNT(todos.id) AS open_todos FROM users LEFT JOIN todos ON todos.user_id = users.id AND todos.done = 0 GROUP BY users.id ORDER BY open_todos DESC""").fetchall())
Output
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.

Predict the outputPython

Using the same tables, what does this print?

print(db.execute("SELECT COUNT(*) FROM todos WHERE user_id = 2 AND done = 0").fetchone()[0])
Need a nudge? Hints walk you through it.

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.

Pythoninjection.py
import sqlite3 db = sqlite3.connect(":memory:")db.executescript("""CREATE TABLE todos (id INTEGER PRIMARY KEY, title TEXT, user_id INTEGER);INSERT INTO todos (title, user_id) VALUES ('Ada secret', 1), ('Sam secret', 2);""") search = "x' OR '1'='1" # typed into a search box by an attacker unsafe = f"SELECT title FROM todos WHERE user_id = 1 AND title = '{search}'"print("f-string:", db.execute(unsafe).fetchall()) safe = "SELECT title FROM todos WHERE user_id = 1 AND title = ?"print("parameter:", db.execute(safe, (search,)).fetchall())
Output
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.

Quick check
Which line is safe from SQL injection?
Need a nudge? A hint rules out a wrong answer.

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:

app/models.py
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:

app/repository.py
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 todo

db.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 the pairs0/5 matched

Match each SQLAlchemy piece to its job.

Choose an item, then its match on the other side.

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):

app/db/session.py
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 db
One request, one session, one transaction
RouteSessionPostgreSQLget_db() yields a sessionBEGINdb.add(Todo(...))INSERT INTO todos ...COMMITok

The dependency opens a session. It borrows a connection from the engine's pool, which is much faster than opening a new one.

1/6
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 one

Autogenerate 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.

Put it in order5 steps

Order the steps to add a due_date column in production.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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.

Pythonn_plus_one.py
import sqlite3 db = sqlite3.connect(":memory:")db.executescript("""CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);CREATE TABLE todos (id INTEGER PRIMARY KEY, title TEXT, user_id INTEGER);""")db.executemany("INSERT INTO users (id, name) VALUES (?, ?)", [(i, f"user{i}") for i in range(1, 51)])db.executemany("INSERT INTO todos (title, user_id) VALUES (?, ?)", [(f"todo {i}", i % 50 + 1) for i in range(200)]) queries = 0def run(sql, params=()): global queries queries += 1 return db.execute(sql, params).fetchall() # N+1: one query for todos, then one per todo for its ownerfor todo_id, title, user_id in run("SELECT id, title, user_id FROM todos"): owner = run("SELECT name FROM users WHERE id = ?", (user_id,))print("N+1 version:", queries, "queries") queries = 0rows = run("SELECT todos.title, users.name FROM todos JOIN users ON users.id = todos.user_id")print("JOIN version:", queries, "query for", len(rows), "rows") print(db.execute("EXPLAIN QUERY PLAN SELECT * FROM todos WHERE user_id = 7").fetchall())db.execute("CREATE INDEX ix_todos_user_id ON todos (user_id)")print(db.execute("EXPLAIN QUERY PLAN SELECT * FROM todos WHERE user_id = 7").fetchall())
Output
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.

Quick check
A page lists 100 todos with their owner's name and makes 101 queries. What is the usual fix?
Need a nudge? A hint rules out a wrong answer.

Practice

ChallengeMedium

Top authors with SQL

Practice real SQL with the built-in sqlite3 module. Write top_authors(users, posts, min_posts):

  • users is a list of [id, name], posts a 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 least min_posts posts, ordered by post_count descending, then name ascending.

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]]
Python
import sqlite3 def top_authors(users: list, posts: list, min_posts: int) -> list: # Create tables, insert with executemany and ?, then one SELECT with LEFT JOIN + GROUP BY. pass
Key terms
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.