🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Python Database Access: Transactions, Sessions, and N+1

Python DatabaseđŸŸĸ Free Lesson

Python Database Access: Transactions, Sessions, and N+1

Most Python performance and correctness problems that get blamed on the database are actually problems in the code that talks to it: connections left open, commits that never happen, placeholders written for the wrong driver, and an ORM loop that quietly issues one query per row. This lesson works from the bottom up — the DB-API contract, transactions, placeholders — then moves to sessions and the N+1 pattern that is the single most common ORM defect.

What You'll Learn

  • 1Manage connections and cursors so nothing leaks and every write is committed or rolled back
  • 2Choose the right placeholder syntax for the driver you are using
  • 3Explain what a session, an identity map, and lazy loading actually do
  • 4Detect and fix the N+1 query pattern with eager loading or a single join

Connections and cursors: who owns the lifecycle

The DB-API defines a connection and a cursor, and the lifetime of each is your responsibility. A connection represents a session with the server — an authenticated channel that costs money to create — while a cursor represents one statement's execution state. Pooling exists precisely so that connections are reused and cursors stay short-lived; opening a new connection per request without a pool turns a traffic spike into a database connection spike.

python
import sqlite3

conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT UNIQUE)")

try:
    with conn:                       # commits on success, rolls back on error
        conn.execute("INSERT INTO users (name) VALUES (?)", ("alice",))
        conn.execute("INSERT INTO users (name) VALUES (?)", ("alice",))
except sqlite3.IntegrityError as exc:
    print("rejected:", exc)

print(conn.execute("SELECT count(*) FROM users").fetchone()[0])   # 0: rolled back

row = conn.execute("SELECT name FROM users WHERE name = ?", ("carol",)).fetchone()
print(row)                            # None — a missing row is not an error

Two habits cover most incidents. Check the return value of fetchone rather than indexing it, because a query with no match returns None and raises IndexError. And use the connection as a context manager for writes so that an exception mid-batch rolls the transaction back instead of leaving a half-applied change that a later read will treat as truth.

Placeholders differ by driver, and getting it wrong is a bug

Parameterised queries are non-negotiable, but the marker syntax is driver-specific, and a string that works against SQLite can raise a syntax error — or worse, silently mis-bind — against PostgreSQL or MySQL. Learn the one your driver uses and never interpolate manually.

DriverPlaceholderStyleExample
sqlite3?Positionalexecute("... WHERE id = ?", (42,))
psycopg 2 and 3%sPositional formatexecute("... WHERE id = %s", (42,))
mysql-connector%sPositional formatexecute("... WHERE id = %s", (42,))
SQLAlchemy Core:nameNamedexecute(text("... WHERE id = :id"), {"id": 42})
asyncpg$1Positional numberfetch("... WHERE id = $1", 42)

The psycopg case deserves a warning: because % is its placeholder marker, a query containing a literal percent sign must double it, or you will be fighting IndexError messages that look like a driver bug. Passing a tuple (or a dict for named parameters) is what tells the driver to bind values separately from the SQL text.

Transactions: an explicit contract

A transaction groups statements into an atomic unit, and the isolation level decides what other sessions can see while yours is in flight. The default in most engines is read committed, where each statement sees rows committed by others before it started — which produces the classic lost-update scenario when two processes read a balance, add to it in memory, and write it back.

python
import sqlite3

conn = sqlite3.connect(":memory:", isolation_level=None)
conn.execute("CREATE TABLE accounts (id INTEGER PRIMARY KEY, owner TEXT, balance INTEGER)")
conn.executemany("INSERT INTO accounts (owner, balance) VALUES (?, ?)",
                 [("ada", 100), ("bob", 50)])

def transfer(source, target, amount):
    conn.execute("BEGIN IMMEDIATE")
    try:
        row = conn.execute(
            "SELECT balance FROM accounts WHERE owner = ?", (source,)
        ).fetchone()
        if row is None or row[0] < amount:
            raise ValueError("insufficient funds")
        conn.execute("UPDATE accounts SET balance = balance - ? WHERE owner = ?",
                     (amount, source))
        conn.execute("UPDATE accounts SET balance = balance + ? WHERE owner = ?",
                     (amount, target))
    except Exception:
        conn.execute("ROLLBACK")
        raise
    else:
        conn.execute("COMMIT")


transfer("ada", "bob", 30)
print(conn.execute("SELECT owner, balance FROM accounts ORDER BY owner").fetchall())

The pattern to internalise is that every BEGIN has exactly one COMMIT or ROLLBACK on every path, including exceptions raised by your own checks. Long transactions are their own hazard: holding locks while you call an external API turns a slow third party into a stalled application, so keep transaction scopes tight and do network work outside them.

Sessions, identity maps, and lazy loading

An ORM session is a unit of work: objects you fetched are tracked, changes are queued, and one commit flushes everything in a predictable order. The identity map behind it guarantees that two queries returning the same primary key give you the same Python object within a session, which prevents surprising duplicate instances and lets the session know exactly what to write on commit.

python
from sqlalchemy import create_engine, select
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship, Session


class Base(DeclarativeBase):
    pass


class Author(Base):
    __tablename__ = "authors"
    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str]
    books: Mapped[list["Book"]] = relationship(back_populates="author")


class Book(Base):
    __tablename__ = "books"
    id: Mapped[int] = mapped_column(primary_key=True)
    title: Mapped[str]
    author_id: Mapped[int]
    author: Mapped[Author] = relationship(back_populates="books")


engine = create_engine("sqlite+pysqlite:///:memory:")
Base.metadata.create_all(engine)

with Session(engine) as session:
    author = Author(name="Ada", books=[Book(title="Notes")])
    session.add(author)
    session.commit()
    print(session.get(Author, author.id).books[0].title)

Lazy loading is the sharp edge. Accessing author.books when the relationship was not loaded fires a query on the spot — convenient in a template, disastrous inside a loop over a thousand authors. That is the N+1 pattern.

Fixing the N+1 query storm

N+1 means one query for the list plus one query per row when you touch a relationship. It is invisible in development with three rows and catastrophic in production with thirty thousand.

python
from sqlalchemy import select
from sqlalchemy.orm import Session, selectinload

# N+1: one query for authors, then one per author for books
with Session(engine) as session:
    for author in session.scalars(select(Author)):
        print(author.name, [b.title for b in author.books])

# Eager load: authors plus a single query for every book
stmt = select(Author).options(selectinload(Author.books))
with Session(engine) as session:
    for author in session.scalars(stmt):
        print(author.name, [b.title for b in author.books])

Two fixes are usually available. Eager loading (selectinload issues one extra query for the whole set, joinedload folds it into a join) keeps the object graph intact at the cost of a wider result. Or restructure the read as a single explicit query returning rows shaped for the caller, which is often simpler when the view only needs three columns and never touches the objects again. Enable query logging in development so the pattern is visible before it ships.

Pooling, timeouts, and what happens when the database stalls

A pooled engine fixes a pool size, and that size must be smaller than the database's connection limit divided across every service that shares it. Oversized pools look harmless under load tests and then saturate the server, at which point every request queues behind a connection that is itself waiting. Set both a connection timeout and a statement timeout: the first fails fast when the database is unreachable, the second stops one accidental full-table scan from holding a worker and its connection indefinitely.

Watch for the classic coupling as well. A pool of twenty connections combined with a web server running fifty workers simply moves the queue from the database to your application, where it is much harder to see. Pool events — checkouts, checkins, timeouts — are worth logging, because a pool that is always full tells you the bottleneck is downstream even when the CPU graph looks idle. The same discipline applies to the session: create it per unit of work, close it in a finally or a context manager, and never cache one on a module for the lifetime of the process.

Raw SQL or ORM, and keeping the schema honest

Neither tool is the default answer. Raw SQL gives you exact control over the plan, makes window functions and bulk operations straightforward, and keeps the query visible in review; it costs you mapping code, migration discipline, and the injection risk that returns the moment someone concatenates. The ORM gives you relationships, identity, and change tracking; it costs you a learning curve, surprising queries, and the temptation to hide expensive work behind attribute access.

NeedPrefer
Complex reporting or analyticsRaw SQL or Core expressions
CRUD over a rich object graphORM
Bulk import of millions of rowsCore executemany or a database copy
Read models for a single endpointA short explicit query
Tracing exactly what runs in productionExplicit SQL you can log and index against

Whichever you choose, the schema must move through migrations. Editing tables by hand works until two environments disagree, at which point the deployment itself becomes an investigation. Alembic with SQLAlchemy produces versioned, ordered migration scripts, supports autogenerate diffs against your models, and gives every environment the same path from its current state to the target one.

Common Mistakes

Opening a new database connection for every request

Fix: Use a pooled engine sized to the database's connection limit, and keep sessions short-lived

Copying placeholder syntax between drivers

Fix: Check the driver's documentation: ?, %s, :name and $1 are all valid somewhere and wrong elsewhere

Performing network calls inside an open transaction

Fix: Fetch what you need, commit or roll back, then call the external service; long transactions hold locks

Iterating over a relationship and assuming it is already loaded

Fix: Eager-load with selectinload or joinedload, or replace the loop with one explicit query

Best Practices

  • Keep transactions tight and make every code path end in commit or rollback
  • Log SQL in development so N+1 patterns and unexpected table scans are visible immediately
  • Let the ORM track changes and commit once per unit of work rather than after every statement
  • Version the schema with migrations and run them as a deployment step, never by hand
  • Index the columns your queries filter and sort on, then confirm with EXPLAIN rather than intuition

Interview Questions

Q1: What is the difference between a connection and a cursor?

A connection is the authenticated session with the server and is expensive to create, so it is pooled. A cursor represents the execution state of one statement; it is cheap and short-lived.

Q2: What causes the N+1 problem and how do you fix it?

Accessing a lazy relationship inside a loop over the parent rows, which issues one query per row. Fix it by eager-loading the relationship with selectinload or joinedload, or by writing a single query that returns exactly the fields needed.

Q3: Why does read committed still allow lost updates?

Because each statement only sees data committed before it began; two transactions can read the same row, compute independently, and last-writer-wins on update. Row locks, optimistic version columns, or a higher isolation level are the remedies.

Q4: When would you bypass the ORM?

For bulk operations, analytical queries with window functions or CTEs, and read models where you want a narrow projection — anywhere you need control over the plan or the volume makes object mapping wasteful.

Key Takeaways

  • Connections are pooled and long-lived; cursors are per-statement, and both lifecycles are yours to manage
  • Every transaction ends in commit or rollback on every path, including your own validation errors
  • Placeholder syntax belongs to the driver; parameterisation is mandatory either way
  • A session is a unit of work with an identity map, and lazy relationships are where N+1 is born
  • Eager loading or a single explicit query fixes N+1; migrations keep every environment's schema in agreement
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement