Python Tutorial 0/52 lessons ~6 min read Lesson 45

    SQLAlchemy ORM & Transactions

    For production data layers, Python teams commonly use SQLAlchemy for modeling, querying, migrations, and transaction boundaries.

    Course progress0%
    Focus
    9 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    For production data layers, Python teams commonly use SQLAlchemy for modeling, querying, migrations, and transaction boundaries.

    Understanding the topic

    Core concepts to understand:

    • Use declarative models with typed columns.
    • Session = unit of work; keep transaction scope tight.
    • Use explicit commit/rollback and retry transient errors.
    • For async APIs, pair FastAPI with async SQLAlchemy engines.

    Syntax reference

    Visual flow / code:

    python
    from sqlalchemy import create_engine, Integer, String
    from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session
    engine = create_engine("postgresql+psycopg://user:pass@localhost/app")
    class Base(DeclarativeBase):
    pass
    class User(Base):
    __tablename__ = "users"
    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    email: Mapped[str] = mapped_column(String(255), unique=True)
    Base.metadata.create_all(engine)
    with Session(engine) as session:
    try:
    session.add(User(email="a@example.com"))
    session.commit()
    except Exception:
    session.rollback()
    raise

    Execution workflow

    1SQLAlchemy ORM & Transactions Workflow
    1 / 4

    Use declarative models with typed columns

    Use declarative models with typed columns.

    Real-world use

    Most Python microservices are API + Postgres. SQLAlchemy gives safe transaction handling and database portability without sacrificing SQL power.

    Best practices

    • One session per request/job.
    • Use migrations (Alembic).
    • Avoid long-lived transactions.
    • Index frequently queried fields.

    Common mistakes

    • Global shared sessions cause race conditions.
    • N+1 queries without eager loading.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1IntermediateQuestionSession lifecycle?+

    Answer

    A Session is a unit of work that tracks ORM objects. Objects move from transient to pending (after add) to persistent (after flush), and later detached when the session closes. Changes are sent to the database on flush, which also happens automatically before queries by default; commit flushes and ends the transaction. Create one session per request or unit of work, use it in a context manager, and close it afterward.

    Follow-up

    What does expire_on_commit do?
    2IntermediateQuestionWhat is N+1 and how to fix it?+

    Answer

    N+1 happens when you run one query to load N parent rows, then lazy loading issues one more query per parent to fetch a relationship, giving N+1 queries total. Fix it with eager loading: selectinload (a second query using IN), joinedload (a JOIN), or by selecting only the columns you need. Turn on SQL echo or query counting in tests to detect it.

    Follow-up

    When is selectinload better than joinedload?
    3IntermediateQuestionORM vs raw SQL trade-offs?+

    Answer

    An ORM maps rows to objects, reduces boilerplate, helps with portability, and manages relationships and transactions, but it can hide inefficient queries and make complex reporting queries awkward. Raw SQL gives full control over the query and database-specific features, but you manage mapping, parameters, and schema changes yourself. Many teams use the ORM for CRUD and SQL, or SQLAlchemy Core, for heavy queries. Always use bound parameters.

    Follow-up

    How do you run raw SQL safely in SQLAlchemy?

    Summary

    In summary: Treat session as unit-of-work. Transaction boundaries are architecture decisions.

    Ready to mark this lesson complete?Track your journey across the entire course.