Skip to content

Queries in Practice: Filtering, Pagination, exists, Counts, Date Ranges, Cascade Rules ​

"When using LIMIT, it is important to use an ORDER BY clause that constrains the result rows into a unique order. Otherwise you will get an unpredictable subset of the query's rows." — PostgreSQL documentation, "7.6. LIMIT and OFFSET", postgresql.org/docs/current/queries-limit.html

Summary: A list endpoint is a filter, a sort, a page and a count. This chapter shows how each part is written with SQLAlchemy 2 and SQLModel so that it stays correct and fast as the table grows. Query parameters go into a Pydantic filter model and come out as where() conditions. Pages are offset pages (with a total) or keyset pages (with a next_cursor). "Is there one?" is exists(), "how many?" is func.count(), never len(). Ratings come from func.avg with group_by/having or a correlated scalar subquery. Bookings use half-open date-range overlap, timestamps are timezone-aware, and deletes follow explicit cascade rules (ORM cascade, ON DELETE, passive_deletes, soft delete). The proof that a list endpoint has no N+1 is a measured query count from a before_cursor_execute event listener. Focus: where, and_, or_, not_, in_, is_, like/ilike/icontains with escaping; FastAPI query parameter models and Depends filters; order_by, desc, nulls_last and unique tie-breakers; limit/offset and the pagination envelope; keyset (seek method) pagination with row values and opaque cursors; EXPLAIN QUERY PLAN, the index for ORDER BY, covering indexes; exists()/select(exists()); func.count vs len(); scalar and correlated subqueries; func.avg, group_by, having, label; join/outerjoin vs loader options, contains_eager; any()/has()/contains(); between and date-range overlap; DateTime(timezone=True), Pydantic AwareDatetime; bulk update()/delete() and synchronize_session; cascade="all, delete-orphan", ondelete, passive_deletes; soft delete with with_loader_criteria; N+1 in list endpoints; bound parameters, text() and SQL injection; Laravel paginate()/cursorPaginate()/whereHas/withCount/chunk and Go sqlc/squirrel comparisons. Learning goal: Build a GET /rooms that validates every query parameter, filters with bound parameters only, sorts deterministically, pages by offset or by cursor with the right index behind it, answers counts and averages in SQL, finds free rooms with one overlap query, stores instants in UTC, deletes along rules you chose on purpose, and has a test that fails the day someone adds an N+1.

This page builds on SQLAlchemy 2 & SQLModel, which owns the engine, the session, the models, relationships and loading strategies, and reuses its Room/Booking/Review domain. Here the subject is the queries a real API sends. It does not re-teach its neighbours: pagination as a database design question (offset vs keyset in PostgreSQL and MySQL, deferred joins) is in Pagination: Offset vs Keyset; index design in Indexing; the worked plan examples in the SQL Queries & Indexes Cheatsheet; ORM failure modes across ORMs in ORM Pitfalls; query-parameter and body models in Request Validation; Depends in Dependency Injection; migrations and the indexes they create in Alembic Migrations, Transactions & Indexes; and the assembled API in Project: Rooms & Bookings API. The Go side of the same queries is database/sql and pgx.

Facts below were checked against the SQLAlchemy 2.0 documentation (unified tutorial "Using SELECT Statements", the ORM query guide for SELECT, relationships and ORM-enabled INSERT/UPDATE/DELETE, column elements, functions, operators, cascades, session basics and session events, core events, the SQLite dialect page), the SQLModel tutorial (where, limit and offset, cascade delete), FastAPI's query parameter, query parameter model and dependency tutorials, Pydantic's type docs (AwareDatetime), Markus Winand's use-the-index-luke.com ("no offset", fetch-next-page, indexed ORDER BY, covering indexes), the SQLite docs (EXPLAIN QUERY PLAN, SELECT, datatypes, row values, the query planner, foreign keys), the PostgreSQL docs (LIMIT/OFFSET, ORDER BY, aggregates, constraints, date/time types, range types), the MySQL 8.4 manual (LIMIT optimisation, foreign keys), the Laravel 13 query builder, pagination and Eloquent pages, the sqlc docs, the Squirrel README and the OWASP SQL injection pages. The page is written for Python 3.12+ and current releases. The snippets ran on the only interpreter on the build machine, CPython 3.9.6, with the same pins as the ORM chapter: SQLAlchemy 2.0.58, SQLModel 0.0.34, FastAPI 0.128.8, Starlette 0.49.3, Pydantic 2.13.5, Uvicorn 0.39.0, httpx 0.28.1 and pytest 8.4.2. Every SQL line, query plan, timing and query count marked "real" is what those runs printed against SQLite 3.54.0. PostgreSQL and MySQL behaviour is from their docs and marked "expected, not run".

Page map ​

If you are looking forGo to
The tables you can memorise in one minuteEverything in one minute
Why list endpoints go wrongWhy it exists
From LIMIT to cursors and query modelsWhere it comes from
A before/after GET /roomsPython
where, and_, or_, not_, in_, is_Filtering
like, ilike, icontains, wildcardsText search
?city=a&city=b into a Pydantic modelFilter models from query parameters
order_by, desc, nulls_last, tie-breakersOrdering
limit, offset, totalOffset pagination
next_cursor, seek method, row valuesKeyset pagination
Why the page query is slow, EXPLAIN QUERY PLANIndexes behind ORDER BY and pages
"Is there at least one?"exists
count() vs len()Counting
A value per row from another tableScalar and correlated subqueries
func.avg, group_by, having, labelAggregates
Filtering with a join vs loading with an optionJoins vs loading
any(), has(), contains()Filtering by related rows
Is the room free between two dates?Date ranges
DateTime(timezone=True), AwareDatetime, UTCTimezone-aware datetimes
update(), delete(), synchronize_sessionBulk update and delete
cascade_delete, ondelete, passive_deletesCascade rules
deleted_at, hiding deleted rows everywhereSoft delete
Proving a list endpoint has no N+1N+1 in list endpoints and query counts
text(), bound parameters, injectionSQL injection safety
The SQL, plans and timings the snippets producedMechanics
The common bugs and their fixesSolving the classic problems
Offset or keyset, join or any, ORM or SQLChoosing
Monolith to distributed systemIn architecture
Reproduce it on your machineLab
paginate(), cursorPaginate(), whereHas, withCountFor PHP/Laravel developers
sqlc, squirrelThe Go angle

Everything in one minute ​

The parts of a list endpoint. Each row is unpacked in the concept catalogue.

PartSQLAlchemy / FastAPISQL (SQLite, real)Rule
Validate inputf: Annotated[RoomFilter, Query()]noneunknown or out-of-range parameter = 422
Filterstmt.where(and_(*conditions))WHERE ... AND ...values only as bound parameters
Text searchcol(Room.name).icontains(q, autoescape=True)lower(room.name) LIKE '%' || lower(?) || '%' ESCAPE '/'escape % and _
Related rowscol(Room.amenities).any(Amenity.name == x)EXISTS (SELECT 1 FROM amenity, roomamenitylink WHERE ...)no join, no duplicates
Sort.order_by(col(Room.price_cents), col(Room.id))ORDER BY room.price_cents, room.idend with a unique column
Offset page.limit(20).offset(40)LIMIT ? OFFSET ?cost grows with the offset
Keyset page.where(tuple_(price, id) > tuple_(p, i)).limit(21)WHERE (room.price_cents, room.id) > (?, ?)constant cost, no page numbers
Totalselect(func.count()).select_from(stmt.order_by(None).subquery())SELECT count(*) AS count_1 FROM (SELECT ...) AS anon_1one more query per page
Load children.options(selectinload(Room.bookings))SELECT ... WHERE booking.room_id IN (?, ?)2 statements for the page
EnvelopePage[RoomPublic] / CursorPage[RoomPublic]noneitems + total or next_cursor

Questions and the query that answers them (all real on the seed data).

QuestionWriteNotStatements
Does the Garden have bookings?select(exists().where(Booking.room_id == g))len(room.bookings) > 01, returns one boolean
How many bookings?select(func.count()).select_from(Booking).where(...)len(session.exec(select(Booking)...).all())1, returns one integer
Average rating per roomcorrelated scalar_subquery() column or group_bya Python loop1
Cities with at least 2 rooms.group_by(Room.city).having(func.count(Room.id) >= 2)filter in Python1
Rooms with zero bookings, counted.outerjoin(Booking) + func.count(Booking.id).join(Booking) (drops them)1
Free between Dec 3 and Dec 4?~exists().where(start < end_ AND end > start_)two separate checks1
Rooms with wifi AND kitchenany() twicejoin + in_ (means OR)1

Deletes and what runs (real, foreign keys ON).

OperationORM cascadeON DELETE CASCADELoaded objects
session.delete(room)runs: selects and deletes bookings, link rowsremoves reviews (passive_deletes="all")deleted state
session.exec(delete(Room).where(...))never runsremoves bookings, reviews, link rowssynchronised by synchronize_session
Same with SQLite foreign keys OFFnever runsdoes not fire eitherorphans left (3 bookings, 3 reviews)
Soft delete (deleted_at = now)not a deletenot a deleterow stays, every query filters it

Why it exists ​

The first version of a list endpoint is always correct on the developer's laptop. It loads every row, counts them with len(), slices the list in Python, and reads room.bookings inside the loop. With six rows that is seven statements and a millisecond. With sixty thousand rows it is sixty thousand and one statements, the whole table in memory, and a timeout. Nothing in the code changed; the data did. Every concept on this page exists because a query that is fine at 10 rows is wrong or slow at 10 million, and the database can do the work better than Python if you ask it the right question.

SimplerBetter at scale
len(rows)func.count() in the database
Load and check if rows:exists(), which stops at the first row
OFFSET pages with page numbersKeyset pages: constant cost, stable under inserts, no page numbers
ORDER BY priceORDER BY price, id (deterministic)
join to filterany()/has() (EXISTS, no duplicate rows)
ondelete nowhere, ORM cascade onlyDatabase ON DELETE plus passive_deletes
Naive datetimeAware datetime, stored as UTC
f-string SQLBound parameters, always

Everyday picture: a library catalogue. A filter is the card you hand to the librarian ("science fiction, after 1990, in English"). Sorting is the order of the drawer. An offset page is "skip the first 400 cards and give me the next 20", so the librarian counts 400 cards every time. A keyset page is "give me the 20 cards after Dune, Herbert", so the librarian opens the drawer at that card. exists() is "do you have at least one?" and the librarian stops at the first card. count() is the number written on the drawer label. len() is carrying the whole drawer to your desk to count it. Cascades are the rule for what happens to the loan cards when a book is withdrawn: shredded by the librarian (ORM cascade), shredded by the building's rules (ON DELETE CASCADE), or the book is just marked "withdrawn" (soft delete). The picture is reused below.

Three common misunderstandings, up front ​

  1. "OFFSET is free because the database skips rows." It does not skip them, it produces and throws them away. PostgreSQL: "The rows skipped by an OFFSET clause still have to be computed inside the server; therefore a large OFFSET might be inefficient." The snippet measured 0.03 ms at depth 0 and 2.19 ms at depth 199,000 with an index, and 83.43 ms at depth 199,000 without one (real).
  2. "Keyset pagination is just WHERE id > ?." That works only when you sort by id. Sorting by price needs the full key (price_cents, id), and the way you write the comparison decides whether the index is used. The plain price > ? OR (price = ? AND id > ?) form was a SCAN in SQLite and slower than OFFSET (4.23 ms); the row-value form and the form with a leading price_cents >= ? were a SEARCH at 0.04 ms (real, runs/explain-query-plan.txt and runs/round2.txt, Indexes).
  3. "Deleting through the ORM and deleting with delete() are the same." session.delete(room) runs the ORM cascade; session.exec(delete(Room).where(...)) is one SQL statement and runs only what the database's foreign keys say. On SQLite with foreign keys off (the default per connection), the second leaves orphans (real, Cascade rules).

Where it comes from ​

LIMIT n OFFSET m is the vendor syntax of MySQL, PostgreSQL and SQLite. The standard form came later: use-the-index-luke notes that the offset keyword "was even taken into the SQL standard as part of the fetch first extension", which SQL Server adopted in 2012 and Db2 (offset) in release 11.1. Row-value constructors are older standard SQL ("Specify an ordered set of values to be constructed into a row or partial row", SQL:92 §7.1, quoted on use-the-index-luke), but support arrived slowly: PostgreSQL uses row-value predicates for index access since 8.4, SQLite has row values since 3.15.0 (2016-10-14), and per the same page MySQL "evaluates row value expressions correctly but cannot use them as access predicate during an index access". Markus Winand named the alternative to offset the "seek method": "The second method, which I call the seek method, searches the last entry of the previous page and fetches only the following rows." His "no offset" post (2014-08-06) argues that "big offsets impose a lot of work on the database—no matter whether SQL or NoSQL." Frameworks followed: Laravel 13 has paginate(), simplePaginate() and cursorPaginate(); FastAPI added query parameter models ("This is supported since FastAPI version 0.115.0"); SQLAlchemy 2.0 made select() the single query API for Core and ORM, including ORM-enabled update()/delete() with synchronize_session='auto' as the default.

     when       event                                                            source (saved)
1    SQL:92     row value constructors in the standard                           use-the-index-luke, fetch-next-page
2    PG 8.4     PostgreSQL uses row-value predicates for index access             use-the-index-luke, fetch-next-page
3    2012       SQL Server adopts OFFSET ... FETCH (the standard fetch first form)   use-the-index-luke, fetch-next-page
4    2014-08    "No offset" post, the seek method made popular                    use-the-index-luke.com/no-offset
5    2016-10    SQLite 3.15.0: row values                                         sqlite.org/rowvalue
6    0.115.0    FastAPI: Pydantic models for query parameters                     fastapi.tiangolo.com, query-param-models
7    2026-11    SQLAlchemy 2.0.58 (maintenance) next to 2.1; Laravel 13 cursorPaginate()  docs pages as fetched

Python ​

Before ​

The list endpoint most people write first. It loads every room to compute total and slices the list in Python, has no ORDER BY, no upper bound on limit, reads room.bookings lazily for each room, shows soft-deleted rooms, and pastes the search text into SQL:

py
"""The list endpoint most people write first. It works on ten rows and fails on ten thousand.

- total = len(all rows), loaded as objects
- no ORDER BY, so OFFSET pages are not deterministic
- bookings read lazily per room: N+1
- the search pastes user input into SQL text
"""

from typing import Annotated, Any, Dict, List, Optional

from fastapi import FastAPI, Query
from sqlalchemy import text
from sqlalchemy.engine import Engine
from sqlmodel import Session, select

from app.models import Room


def create_before_app(engine: Engine) -> FastAPI:
    app = FastAPI(title="Rooms (before)")

    @app.get("/rooms")
    def list_rooms(
        limit: Annotated[int, Query()] = 20,  # no upper bound: ?limit=1000000 is accepted
        offset: int = 0,
        q: Optional[str] = None,
    ) -> Dict[str, Any]:
        with Session(engine) as session:
            if q:
                # SQL injection: q=' OR 1=1 -- returns every room
                sql = text(f"SELECT id FROM room WHERE name LIKE '%{q}%'")
                ids = [r[0] for r in session.execute(sql)]
                rooms = [session.get(Room, i) for i in ids]
            else:
                rooms = list(session.exec(select(Room)).all())  # every row, every time
            total = len(rooms)
            page = rooms[offset : offset + limit]  # paging in Python, after loading everything
            items: List[Dict[str, Any]] = []
            for room in page:
                items.append(
                    {
                        "id": room.id,
                        "name": room.name,
                        "bookings": [b.id for b in room.bookings],  # lazy load: 1 SELECT per room
                    }
                )
            return {"items": items, "total": total}

    return app

The tests pin each problem: 1 + 6 statements for six rooms, all 26 rows loaded to return two, no LIMIT in the SQL, and q=' OR 1=1 -- returning every room:

py
from typing import Iterator

import pytest
from fastapi.testclient import TestClient

from app.before import create_before_app
from app.models import Room
from app.querycount import count_queries
from sqlmodel import Session


@pytest.fixture
def before(engine, ids) -> Iterator[TestClient]:  # type: ignore[no-untyped-def]
    with TestClient(create_before_app(engine)) as c:
        yield c


def test_before_is_n_plus_one(before: TestClient, engine) -> None:  # type: ignore[no-untyped-def]
    with count_queries(engine) as log:
        body = before.get("/rooms", params={"limit": 100}).json()
    assert body["total"] == 6  # the soft-deleted Attic is counted and shown
    assert log.count == 1 + 6  # one SELECT of every room, one SELECT per room for bookings


def test_before_grows_with_the_table(before: TestClient, engine) -> None:  # type: ignore[no-untyped-def]
    with Session(engine) as s:
        s.add_all([Room(name=f"Extra {i}", city="Yazd", capacity=1, price_cents=1000 + i) for i in range(20)])
        s.commit()
    with count_queries(engine) as log:
        before.get("/rooms", params={"limit": 2})
    # Only 2 items returned, yet all 26 rows were loaded to compute total and slice in Python
    assert log.count == 1 + 2
    assert "LIMIT" not in log.statements[0]


def test_before_search_is_injectable(before: TestClient) -> None:
    body = before.get("/rooms", params={"q": "' OR 1=1 --"}).json()
    assert body["total"] == 6

After ​

The models: the ORM chapter's domain plus a deleted_at soft-delete column, a UTCDateTime type that keeps instants correct on SQLite, a composite (price_cents, id) index for the keyset sort and a (room_id, start_date) index for the overlap check:

py
"""Rooms, bookings, reviews, users, amenities: the data layer of the SQLAlchemy & SQLModel
chapter, plus what this chapter needs on top of it: a soft-delete column, a timezone-aware
timestamp type, and the composite indexes the pagination and overlap queries rely on.

No `from __future__ import annotations`: SQLModel and FastAPI read annotations at runtime.
"""

import datetime as dt
from typing import Any, List, Optional

from sqlalchemy import Column, DateTime, Index
from sqlalchemy.types import TypeDecorator
from sqlmodel import Field, Relationship, SQLModel


def utcnow() -> dt.datetime:
    return dt.datetime.now(dt.timezone.utc)


class UTCDateTime(TypeDecorator):  # type: ignore[type-arg]
    """DateTime(timezone=True) that also survives SQLite.

    PostgreSQL's timestamptz keeps the instant. SQLite has no datetime type: SQLAlchemy stores
    an ISO string and DROPS the offset, so 10:00+03:30 comes back as a naive 10:00. This type
    converts every aware value to UTC before binding and marks results as UTC when reading.
    Naive input is rejected: it is the bug, not a value.
    """

    impl = DateTime(timezone=True)
    cache_ok = True

    def process_bind_param(self, value: Optional[dt.datetime], dialect: Any) -> Optional[dt.datetime]:
        if value is None:
            return None
        if value.tzinfo is None or value.utcoffset() is None:
            raise ValueError("naive datetime: pass an aware datetime (UTC)")
        return value.astimezone(dt.timezone.utc)

    def process_result_value(self, value: Optional[dt.datetime], dialect: Any) -> Optional[dt.datetime]:
        if value is None:
            return None
        if value.tzinfo is None:  # SQLite: stored as UTC without an offset
            return value.replace(tzinfo=dt.timezone.utc)
        return value.astimezone(dt.timezone.utc)


class User(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    email: str = Field(index=True, unique=True, max_length=255)
    # ON DELETE SET NULL in the database; passive_deletes=True: the ORM does not load
    # unloaded bookings just to null their user_id, the database does it.
    bookings: List["Booking"] = Relationship(back_populates="user", passive_deletes=True)


class RoomAmenityLink(SQLModel, table=True):
    room_id: Optional[int] = Field(default=None, foreign_key="room.id", primary_key=True, ondelete="CASCADE")
    amenity_id: Optional[int] = Field(
        default=None, foreign_key="amenity.id", primary_key=True, ondelete="CASCADE"
    )


class Amenity(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    name: str = Field(unique=True, max_length=50)
    rooms: List["Room"] = Relationship(back_populates="amenities", link_model=RoomAmenityLink)


class RoomBase(SQLModel):
    name: str = Field(index=True, unique=True, max_length=100)
    city: str = Field(max_length=50)
    capacity: int = Field(ge=1, le=50)
    price_cents: int = Field(ge=0)


class Room(RoomBase, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    # Soft delete: a timestamp instead of a DELETE. NULL means "live".
    deleted_at: Optional[dt.datetime] = Field(default=None, sa_column=Column(UTCDateTime(), nullable=True))
    # ORM cascade "all, delete-orphan" (cascade_delete=True) plus ON DELETE CASCADE on booking.room_id.
    bookings: List["Booking"] = Relationship(back_populates="room", cascade_delete=True)
    # Database-only cascade: passive_deletes="all", the ORM never loads reviews to delete them.
    reviews: List["Review"] = Relationship(back_populates="room", passive_deletes="all")
    amenities: List[Amenity] = Relationship(back_populates="rooms", link_model=RoomAmenityLink)

    # The keyset (seek) index: ORDER BY price_cents, id is read straight from it.
    __table_args__ = (Index("ix_room_price_id", "price_cents", "id"),)


class RoomPublic(RoomBase):
    id: int


class Booking(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    room_id: int = Field(foreign_key="room.id", ondelete="CASCADE")
    user_id: Optional[int] = Field(default=None, foreign_key="user.id", ondelete="SET NULL")
    start_date: dt.date
    end_date: dt.date  # exclusive: [start_date, end_date)
    guests: int = Field(default=1, ge=1)
    created_at: dt.datetime = Field(default_factory=utcnow, sa_column=Column(UTCDateTime(), nullable=False))
    room: Optional[Room] = Relationship(back_populates="bookings")
    user: Optional[User] = Relationship(back_populates="bookings")

    # Serves "bookings of room X that overlap [a, b)": equality column first, then the range column.
    __table_args__ = (Index("ix_booking_room_start", "room_id", "start_date"),)


class Review(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    room_id: int = Field(foreign_key="room.id", index=True, ondelete="CASCADE")
    rating: int = Field(ge=1, le=5)
    room: Optional[Room] = Relationship(back_populates="reviews")

The engine factory (SQLite foreign keys ON) and the per-request session:

py
"""Engine factory with SQLite foreign keys ON, and the per-request session dependency."""

from typing import Annotated, Any, Iterator

from fastapi import Depends, Request
from sqlalchemy import event
from sqlalchemy.engine import Engine
from sqlalchemy.pool import StaticPool
from sqlmodel import Session, SQLModel, create_engine


def _fk_on(dbapi_connection: Any, connection_record: Any) -> None:
    """SQLite ships with foreign keys OFF per connection; ON DELETE CASCADE needs them ON."""
    cursor = dbapi_connection.cursor()
    cursor.execute("PRAGMA foreign_keys=ON")
    cursor.close()


def make_engine(url: str = "sqlite://", *, echo: bool = False) -> Engine:
    kwargs: Any = {"echo": echo}
    if url.startswith("sqlite"):
        kwargs["connect_args"] = {"check_same_thread": False}
        if url in ("sqlite://", "sqlite:///:memory:"):
            kwargs["poolclass"] = StaticPool
    engine = create_engine(url, **kwargs)
    if url.startswith("sqlite"):
        event.listen(engine, "connect", _fk_on)
    return engine


def create_db_and_tables(engine: Engine) -> None:
    """Tests and demos only; production schemas are owned by Alembic."""
    SQLModel.metadata.create_all(engine)


def get_engine(request: Request) -> Engine:
    return request.app.state.engine


def get_session(engine: Annotated[Engine, Depends(get_engine)]) -> Iterator[Session]:
    with Session(engine) as session:
        try:
            yield session
        except Exception:
            session.rollback()
            raise


SessionDep = Annotated[Session, Depends(get_session)]

The filter model and its translation into where() conditions and a deterministic order_by:

py
"""Query parameters -> a Pydantic filter model -> WHERE clauses.

FastAPI reads the model from the query string with `Annotated[RoomFilter, Query()]`
(query parameter models, FastAPI 0.115+). The model validates; `apply_room_filter`
only translates. Every user value becomes a bound parameter, never SQL text.
"""

import datetime as dt
from typing import Any, List, Literal, Optional

from pydantic import BaseModel, ConfigDict, Field, model_validator
from sqlalchemy import and_, exists, func, not_, nulls_last, or_, select as sa_select
from sqlmodel import col

from app.models import Amenity, Booking, Review, Room
from app.queries import overlaps

SortKey = Literal["price", "-price", "name", "rating"]


class RoomFilter(BaseModel):
    # Unknown query parameters are a 422, not silently ignored (?capactiy=2 is a typo).
    model_config = ConfigDict(extra="forbid")

    q: Optional[str] = Field(default=None, min_length=1, max_length=50)
    city: List[str] = []  # ?city=Tabriz&city=Shiraz -> city IN (?, ?)
    exclude_city: Optional[str] = None
    min_capacity: Optional[int] = Field(default=None, ge=1, le=50)
    max_price: Optional[int] = Field(default=None, ge=0)
    amenity: List[str] = []  # every listed amenity must be present
    available_from: Optional[dt.date] = None
    available_to: Optional[dt.date] = None
    include_deleted: bool = False
    sort: SortKey = "price"
    # Paging lives in the same model: with extra="forbid" a separate limit/offset dependency
    # would be rejected as "extra" (the model sees every query parameter of the request).
    limit: int = Field(default=20, ge=1, le=100)
    offset: int = Field(default=0, ge=0, le=10_000)  # a ceiling: deep offsets are the slow ones

    @model_validator(mode="after")
    def check_range(self) -> "RoomFilter":
        if (self.available_from is None) != (self.available_to is None):
            raise ValueError("available_from and available_to go together")
        if self.available_from and self.available_to and self.available_to <= self.available_from:
            raise ValueError("available_to must be after available_from")
        return self


def avg_rating_subquery() -> Any:
    """Correlated scalar subquery: one number per outer room row (NULL with no reviews)."""
    return (
        sa_select(func.avg(Review.rating))
        .where(Review.room_id == Room.id)
        .correlate(Room)
        .scalar_subquery()
    )


def apply_room_filter(stmt: Any, f: RoomFilter) -> Any:
    conditions = []
    if not f.include_deleted:
        conditions.append(col(Room.deleted_at).is_(None))
    if f.q:
        # icontains(autoescape=True): % and _ typed by the user match literally
        conditions.append(
            or_(col(Room.name).icontains(f.q, autoescape=True), col(Room.city).icontains(f.q, autoescape=True))
        )
    if f.city:
        conditions.append(col(Room.city).in_(f.city))
    if f.exclude_city:
        conditions.append(not_(Room.city == f.exclude_city))
    if f.min_capacity is not None:
        conditions.append(Room.capacity >= f.min_capacity)
    if f.max_price is not None:
        conditions.append(Room.price_cents <= f.max_price)
    for name in f.amenity:
        # One EXISTS per amenity: "has wifi AND has kitchen", no join, no duplicate rows.
        conditions.append(col(Room.amenities).any(Amenity.name == name))
    if f.available_from and f.available_to:
        clash = exists().where(Booking.room_id == Room.id, overlaps(f.available_from, f.available_to))
        conditions.append(~clash)
    return stmt.where(and_(*conditions)) if conditions else stmt


def room_order(sort: SortKey) -> List[Any]:
    """Always end with the primary key: a unique tie-breaker makes pages deterministic."""
    if sort == "price":
        return [col(Room.price_cents), col(Room.id)]
    if sort == "-price":
        return [col(Room.price_cents).desc(), col(Room.id).desc()]
    if sort == "name":
        return [col(Room.name)]  # unique already
    return [nulls_last(avg_rating_subquery().desc()), col(Room.id)]

Offset pagination with a total, keyset pagination with an opaque cursor, both envelopes:

py
"""Offset pagination with a total, and keyset (cursor, seek method) pagination with next_cursor."""

import base64
import json
from typing import Any, Generic, List, Optional, Sequence, Tuple, TypeVar

from pydantic import BaseModel
from sqlalchemy import and_, func, or_, select as sa_select, tuple_
from sqlmodel import Session, col

from app.models import Room

T = TypeVar("T")

# Both key columns are INTEGER: SQLite and PostgreSQL BIGINT hold signed 64-bit values.
# A cursor outside that range cannot match any row and would make the driver raise
# (OverflowError on sqlite3), so it is rejected before any SQL is built.
INT64_MIN, INT64_MAX = -(2**63), 2**63 - 1


class Page(BaseModel, Generic[T]):
    """Offset envelope: the client can jump to page N and show "N of M"."""

    items: List[T]
    total: int
    limit: int
    offset: int


class CursorPage(BaseModel, Generic[T]):
    """Keyset envelope: no total, no page numbers, an opaque token for the next page."""

    items: List[T]
    next_cursor: Optional[str]
    limit: int


def paginate_offset(session: Session, stmt: Any, *, limit: int, offset: int) -> Tuple[Sequence[Any], int]:
    """Two statements: COUNT over the filtered query (ORDER BY dropped), then one page."""
    total = session.scalar(sa_select(func.count()).select_from(stmt.order_by(None).subquery())) or 0
    items = session.exec(stmt.limit(limit).offset(offset)).all()
    return items, total


def encode_cursor(price_cents: int, room_id: int) -> str:
    raw = json.dumps([price_cents, room_id]).encode()
    return base64.urlsafe_b64encode(raw).decode().rstrip("=")


def decode_cursor(token: str) -> Tuple[int, int]:
    """Opaque to clients, validated here: a tampered token is a 400, not a 500."""
    try:
        padded = token + "=" * (-len(token) % 4)
        price, rid = json.loads(base64.urlsafe_b64decode(padded.encode()))
        for v in (price, rid):
            # bool is a subclass of int in Python: [true, 1] is not a cursor
            if type(v) is not int or not INT64_MIN <= v <= INT64_MAX:
                raise ValueError
        return price, rid
    except Exception as exc:  # noqa: BLE001 - every decoding failure means the same thing
        raise ValueError("invalid cursor") from exc


def after_key_naive(price_cents: int, room_id: int) -> Any:
    """The seek predicate for ORDER BY price_cents, id, written out with OR / AND.
    Correct, but SQLite (and other planners) cannot turn the OR into an index range: SCAN."""
    return or_(
        col(Room.price_cents) > price_cents,
        and_(col(Room.price_cents) == price_cents, col(Room.id) > room_id),
    )


def after_key(price_cents: int, room_id: int) -> Any:
    """Same rows, plus a redundant leading bound the planner can use as the index start:
    price_cents >= ? AND (price_cents > ? OR price_cents = ? AND id > ?)."""
    return and_(col(Room.price_cents) >= price_cents, after_key_naive(price_cents, room_id))


def after_key_row_value(price_cents: int, room_id: int) -> Any:
    """The same predicate as a row-value comparison: (price_cents, id) > (?, ?)."""
    return tuple_(col(Room.price_cents), col(Room.id)) > tuple_(price_cents, room_id)


def paginate_keyset(
    session: Session, stmt: Any, *, limit: int, cursor: Optional[str], row_values: bool = False
) -> Tuple[Sequence[Room], Optional[str]]:
    if cursor:
        price, rid = decode_cursor(cursor)
        stmt = stmt.where(after_key_row_value(price, rid) if row_values else after_key(price, rid))
    # limit + 1: one extra row answers "is there a next page?" without a COUNT
    rows = session.exec(stmt.order_by(col(Room.price_cents), col(Room.id)).limit(limit + 1)).all()
    page = list(rows[:limit])
    next_cursor = encode_cursor(page[-1].price_cents, page[-1].id) if len(rows) > limit else None  # type: ignore[arg-type]
    return page, next_cursor

The query recipes: overlap, between, aware timestamps, exists, count vs len, correlated subqueries, outerjoin vs join, group_by/having, any/has/contains, join vs contains_eager, bulk update/delete, soft delete, text():

py
"""Query recipes: exists, counts, scalar subqueries, aggregates, date ranges, relationship
filters, joins vs loader options, bulk DML, raw SQL with bound parameters."""

import datetime as dt
from typing import Any, List, Optional, Sequence, Tuple

from sqlalchemy import delete, exists, func, select as sa_select, text, update
from sqlalchemy.orm import contains_eager, selectinload
from sqlmodel import Session, col, select

from app.models import Amenity, Booking, Review, Room, User


# ---------- date ranges ----------


def overlaps(start: dt.date, end: dt.date) -> Any:
    """Half-open [start, end): two ranges overlap when a.start < b.end AND a.end > b.start."""
    return (col(Booking.start_date) < end) & (col(Booking.end_date) > start)


def room_is_free(session: Session, room_id: int, start: dt.date, end: dt.date) -> bool:
    stmt = sa_select(exists().where(Booking.room_id == room_id, overlaps(start, end)))
    return not session.scalar(stmt)


def bookings_starting_between(session: Session, first: dt.date, last: dt.date) -> Sequence[int]:
    """BETWEEN is inclusive on both ends: first <= start_date <= last."""
    stmt = (
        select(Booking.id).where(col(Booking.start_date).between(first, last)).order_by(col(Booking.id))
    )
    return session.exec(stmt).all()


def bookings_created_since(session: Session, since: dt.datetime) -> Sequence[int]:
    """`since` must be aware; UTCDateTime turns it into UTC before it is bound."""
    stmt = select(Booking.id).where(col(Booking.created_at) >= since).order_by(col(Booking.id))
    return session.exec(stmt).all()


def recent_bookings(session: Session, since: dt.datetime, limit: int) -> Sequence[Booking]:
    stmt = (
        select(Booking)
        .where(col(Booking.created_at) >= since)
        .order_by(col(Booking.created_at), col(Booking.id))
        .limit(limit)
    )
    return session.exec(stmt).all()


# ---------- exists and counts ----------


def has_bookings_exists(session: Session, room_id: int) -> bool:
    """SELECT EXISTS (...): the database stops at the first matching row."""
    return bool(session.scalar(sa_select(exists().where(Booking.room_id == room_id))))


def count_bookings(session: Session, room_id: int) -> int:
    """SELECT count(*) ... : one integer crosses the wire."""
    stmt = select(func.count()).select_from(Booking).where(Booking.room_id == room_id)
    return session.exec(stmt).one()


def count_bookings_with_len(session: Session, room_id: int) -> int:
    """The anti-pattern: every row is fetched and turned into an object to be counted."""
    return len(session.exec(select(Booking).where(Booking.room_id == room_id)).all())


def rooms_with_avg_rating(session: Session) -> List[Tuple[str, Optional[float]]]:
    """Correlated scalar subquery as a column: one avg per room, NULL when it has no reviews."""
    avg = (
        sa_select(func.avg(Review.rating))
        .where(Review.room_id == Room.id)
        .correlate(Room)
        .scalar_subquery()
        .label("avg_rating")
    )
    rows = session.exec(select(Room.name, avg).order_by(col(Room.id))).all()
    return [(name, None if a is None else round(float(a), 2)) for name, a in rows]


# ---------- aggregates ----------


def booking_counts_outerjoin(session: Session) -> List[Tuple[str, int]]:
    """LEFT OUTER JOIN + count(booking.id): rooms with zero bookings stay, with 0."""
    n = func.count(col(Booking.id)).label("bookings")
    stmt = (
        select(Room.name, n)
        .outerjoin(Booking, col(Booking.room_id) == Room.id)
        .group_by(col(Room.id), col(Room.name))
        .order_by(n.desc(), col(Room.name))
    )
    return list(session.exec(stmt).all())


def booking_counts_innerjoin(session: Session) -> List[Tuple[str, int]]:
    """Inner JOIN: rooms with zero bookings disappear from the report."""
    n = func.count(col(Booking.id)).label("bookings")
    stmt = (
        select(Room.name, n)
        .join(Booking, col(Booking.room_id) == Room.id)
        .group_by(col(Room.id), col(Room.name))
        .order_by(n.desc(), col(Room.name))
    )
    return list(session.exec(stmt).all())


def city_stats(session: Session, min_rooms: int = 2) -> List[Tuple[str, int, float, int, int]]:
    """GROUP BY city, HAVING count >= min_rooms; labelled aggregates ordered by label."""
    rooms = func.count(col(Room.id)).label("rooms")
    avg_price = func.avg(Room.price_cents).label("avg_price")
    stmt = (
        select(Room.city, rooms, avg_price, func.min(Room.price_cents), func.max(Room.price_cents))
        .where(col(Room.deleted_at).is_(None))
        .group_by(col(Room.city))
        .having(func.count(col(Room.id)) >= min_rooms)
        .order_by(rooms.desc(), col(Room.city))
    )
    return [(c, n, round(float(a), 2), lo, hi) for c, n, a, lo, hi in session.exec(stmt).all()]


# ---------- filtering by related rows ----------


def rooms_with_amenity(session: Session, name: str) -> Sequence[str]:
    """Collection.any(): WHERE EXISTS (SELECT 1 FROM link, amenity WHERE ...)."""
    stmt = select(Room.name).where(col(Room.amenities).any(Amenity.name == name)).order_by(col(Room.name))
    return session.exec(stmt).all()


def rooms_without_bookings(session: Session) -> Sequence[str]:
    """~any(): NOT EXISTS, the anti-join."""
    stmt = select(Room.name).where(~col(Room.bookings).any()).order_by(col(Room.name))
    return session.exec(stmt).all()


def bookings_in_city(session: Session, city: str) -> Sequence[int]:
    """Many-to-one .has(): WHERE EXISTS (SELECT 1 FROM room WHERE room.id = booking.room_id AND ...)."""
    stmt = select(Booking.id).where(col(Booking.room).has(Room.city == city)).order_by(col(Booking.id))
    return session.exec(stmt).all()


def rooms_containing(session: Session, amenity: Amenity) -> Sequence[str]:
    """Collection.contains(obj): rooms whose amenities include this exact object."""
    stmt = select(Room.name).where(col(Room.amenities).contains(amenity)).order_by(col(Room.name))
    return session.exec(stmt).all()


def rooms_booked_by_join(session: Session, user_id: int) -> Sequence[Room]:
    """JOIN to filter + selectinload to load: the filter does NOT narrow room.bookings."""
    stmt = (
        select(Room)
        .join(Booking, col(Booking.room_id) == Room.id)
        .where(Booking.user_id == user_id)
        .options(selectinload(Room.bookings))  # type: ignore[arg-type]
        .distinct()
        .order_by(col(Room.id))
    )
    return session.exec(stmt).all()


def rooms_booked_contains_eager(session: Session, user_id: int) -> Sequence[Room]:
    """JOIN + contains_eager: room.bookings is filled from the joined, filtered rows."""
    stmt = (
        select(Room)
        .join(Booking, col(Booking.room_id) == Room.id)
        .where(Booking.user_id == user_id)
        .options(contains_eager(Room.bookings))  # type: ignore[arg-type]
        .order_by(col(Room.id))
        .execution_options(populate_existing=True)
    )
    return session.exec(stmt).unique().all()


# ---------- bulk DML ----------


def raise_prices(session: Session, city: str, percent: int, sync: Any = "auto") -> int:
    """One UPDATE for every room in the city. synchronize_session decides what happens to
    Room objects already loaded in this session."""
    stmt = (
        update(Room)
        .where(Room.city == city)
        # // is integer division; / would render a float division in SQLAlchemy 2.0
        .values(price_cents=Room.price_cents * (100 + percent) // 100)
        .execution_options(synchronize_session=sync)
    )
    return session.exec(stmt).rowcount  # type: ignore[call-overload,no-any-return]


def raise_prices_in_batches(session: Session, city: str, percent: int, batch: int = 500) -> List[int]:
    """update() has no .limit() in SQLAlchemy 2.0: select a bounded, ordered slice of ids,
    update exactly those, commit, continue after the last id. Returns the batch sizes."""
    sizes: List[int] = []
    last_id = 0
    while True:
        ids = session.exec(
            select(Room.id).where(Room.city == city, col(Room.id) > last_id).order_by(col(Room.id)).limit(batch)
        ).all()
        if not ids:
            return sizes
        session.exec(  # type: ignore[call-overload]
            update(Room)
            .where(col(Room.id).in_(ids))
            .values(price_cents=Room.price_cents * (100 + percent) // 100)
            .execution_options(synchronize_session=False)
        )
        session.commit()  # short transactions: each batch holds its locks briefly
        sizes.append(len(ids))
        last_id = ids[-1]  # type: ignore[assignment]


def delete_rooms_in_city(session: Session, city: str, sync: Any = "auto") -> int:
    """Bulk DELETE: no ORM cascade runs, only the database's ON DELETE actions."""
    stmt = delete(Room).where(Room.city == city).execution_options(synchronize_session=sync)
    return session.exec(stmt).rowcount  # type: ignore[call-overload,no-any-return]


def soft_delete_room(session: Session, room: Room, now: dt.datetime) -> None:
    room.deleted_at = now
    session.add(room)


# ---------- raw SQL ----------


def search_names_text(session: Session, fragment: str) -> List[str]:
    """text() with a named bound parameter: the value never becomes SQL."""
    stmt = text("SELECT name FROM room WHERE name LIKE :pattern ORDER BY name")
    return [r[0] for r in session.execute(stmt, {"pattern": f"%{fragment}%"})]


def search_names_fstring(session: Session, fragment: str) -> List[str]:
    """SQL injection: the user's text is pasted into the statement. Never do this."""
    stmt = text(f"SELECT name FROM room WHERE name LIKE '%{fragment}%' ORDER BY name")
    return [r[0] for r in session.execute(stmt)]


def users_with_bookings(session: Session) -> Sequence[str]:
    stmt = select(User.email).where(col(User.bookings).any()).order_by(col(User.email))
    return session.exec(stmt).all()

Soft delete applied to every SELECT of a session class:

py
"""Soft delete applied to every SELECT of a session class, with do_orm_execute +
with_loader_criteria (the pattern from SQLAlchemy's ORM events documentation)."""

from typing import Any

from sqlalchemy import event
from sqlalchemy.orm import ORMExecuteState, with_loader_criteria
from sqlmodel import Session

from app.models import Room


class SoftDeleteSession(Session):
    """A Session that hides rooms with deleted_at set unless asked not to."""


@event.listens_for(SoftDeleteSession, "do_orm_execute")
def _hide_deleted(state: ORMExecuteState) -> Any:
    if (
        state.is_select
        and not state.is_column_load
        and not state.is_relationship_load
        and not state.execution_options.get("include_deleted", False)
    ):
        state.statement = state.statement.options(
            with_loader_criteria(Room, lambda cls: cls.deleted_at.is_(None), include_aliases=True)
        )

The query counter (a before_cursor_execute event listener):

py
"""Count the statements an engine sends, with a before_cursor_execute event listener.

The listener fires once per DBAPI cursor execution, after SQLAlchemy has compiled the
statement and just before the driver runs it, so it sees exactly what the database sees:
the SQL string with placeholders and the bound parameters next to it.
"""

from contextlib import contextmanager
from typing import Any, Iterator, List, Tuple

from sqlalchemy import event
from sqlalchemy.engine import Engine


class QueryLog:
    def __init__(self) -> None:
        self.entries: List[Tuple[str, Any]] = []

    @property
    def statements(self) -> List[str]:
        return [s for s, _ in self.entries]

    @property
    def count(self) -> int:
        return len(self.entries)

    def selects(self) -> List[str]:
        return [s for s in self.statements if s.startswith("SELECT")]


@contextmanager
def count_queries(engine: Engine) -> Iterator[QueryLog]:
    log = QueryLog()

    def before_cursor_execute(conn, cursor, statement, parameters, context, executemany):  # type: ignore[no-untyped-def]
        if not statement.lstrip().upper().startswith("PRAGMA"):
            log.entries.append((" ".join(statement.split()), parameters))

    event.listen(engine, "before_cursor_execute", before_cursor_execute)
    try:
        yield log
    finally:
        event.remove(engine, "before_cursor_execute", before_cursor_execute)

The application: GET /rooms (filter model + offset envelope), GET /rooms/feed (cursor envelope), GET /rooms/with-bookings (constant query count), availability, city stats, soft DELETE, and an AwareDatetime query parameter:

py
"""List endpoints done right: a filter model from query parameters, offset pages with a
total, keyset pages with next_cursor, eager loading in list endpoints, aware datetimes."""

import datetime as dt
from contextlib import asynccontextmanager
from typing import Annotated, AsyncIterator, List, Optional

from fastapi import Depends, FastAPI, HTTPException, Query, Response, status
from pydantic import AwareDatetime, BaseModel
from sqlalchemy.engine import Engine
from sqlalchemy.orm import selectinload
from sqlmodel import select

from app import queries
from app.db import SessionDep, create_db_and_tables, make_engine
from app.filters import RoomFilter, apply_room_filter, room_order
from app.models import Booking, Room, RoomPublic, utcnow
from app.pagination import CursorPage, Page, paginate_keyset, paginate_offset


class BookingOut(BaseModel):
    id: int
    start_date: dt.date
    end_date: dt.date
    created_at: dt.datetime


class RoomWithBookings(RoomPublic):
    bookings: List[BookingOut]


class Paging(BaseModel):
    limit: int = 20
    offset: int = 0


def paging(
    limit: Annotated[int, Query(ge=1, le=100)] = 20,
    offset: Annotated[int, Query(ge=0, le=10_000)] = 0,
) -> Paging:
    # A ceiling on offset: deep pages are the expensive ones (see keyset pagination).
    return Paging(limit=limit, offset=offset)


FilterDep = Annotated[RoomFilter, Query()]
PagingDep = Annotated[Paging, Depends(paging)]


def create_app(engine: Optional[Engine] = None, database_url: str = "sqlite://") -> FastAPI:
    @asynccontextmanager
    async def lifespan(app: FastAPI) -> AsyncIterator[None]:
        app.state.engine = engine or make_engine(database_url)
        create_db_and_tables(app.state.engine)  # Alembic owns this in production
        yield
        app.state.engine.dispose()

    app = FastAPI(title="Rooms: queries in practice", lifespan=lifespan)

    @app.get("/rooms", response_model=Page[RoomPublic])
    def list_rooms(f: FilterDep, session: SessionDep) -> Page[RoomPublic]:
        stmt = apply_room_filter(select(Room), f).order_by(*room_order(f.sort))
        items, total = paginate_offset(session, stmt, limit=f.limit, offset=f.offset)
        return Page[RoomPublic](
            items=[RoomPublic.model_validate(r) for r in items], total=total, limit=f.limit, offset=f.offset
        )

    @app.get("/rooms/feed", response_model=CursorPage[RoomPublic])
    def room_feed(
        session: SessionDep,
        limit: Annotated[int, Query(ge=1, le=100)] = 20,
        cursor: Optional[str] = None,
    ) -> CursorPage[RoomPublic]:
        stmt = select(Room).where(Room.deleted_at == None)  # noqa: E711 - renders IS NULL
        try:
            items, next_cursor = paginate_keyset(session, stmt, limit=limit, cursor=cursor)
        except ValueError:
            raise HTTPException(status.HTTP_400_BAD_REQUEST, "Invalid cursor")
        return CursorPage[RoomPublic](
            items=[RoomPublic.model_validate(r) for r in items], next_cursor=next_cursor, limit=limit
        )

    @app.get("/rooms/with-bookings", response_model=List[RoomWithBookings])
    def rooms_with_bookings(session: SessionDep, p: PagingDep) -> List[Room]:
        # selectinload: 1 SELECT for the page + 1 SELECT ... IN (...) for all their bookings
        stmt = (
            select(Room)
            .where(Room.deleted_at == None)  # noqa: E711
            .options(selectinload(Room.bookings))  # type: ignore[arg-type]
            .order_by(Room.price_cents, Room.id)
            .limit(p.limit)
            .offset(p.offset)
        )
        return list(session.exec(stmt).all())

    @app.get("/rooms/{room_id}/free")
    def is_free(room_id: int, start: dt.date, end: dt.date, session: SessionDep) -> dict:
        if end <= start:
            raise HTTPException(422, "end must be after start")
        return {"free": queries.room_is_free(session, room_id, start, end)}

    @app.get("/stats/cities")
    def stats(session: SessionDep, min_rooms: Annotated[int, Query(ge=1)] = 2) -> List[dict]:
        return [
            {"city": c, "rooms": n, "avg_price": a, "min_price": lo, "max_price": hi}
            for c, n, a, lo, hi in queries.city_stats(session, min_rooms)
        ]

    @app.delete("/rooms/{room_id}", status_code=status.HTTP_204_NO_CONTENT)
    def soft_delete(room_id: int, session: SessionDep) -> Response:
        room = session.get(Room, room_id)
        if room is None or room.deleted_at is not None:
            raise HTTPException(status.HTTP_404_NOT_FOUND, "Room not found")
        queries.soft_delete_room(session, room, utcnow())
        session.commit()
        return Response(status_code=status.HTTP_204_NO_CONTENT)

    @app.get("/bookings/recent", response_model=List[BookingOut])
    def recent_bookings(
        since: AwareDatetime, session: SessionDep, limit: Annotated[int, Query(ge=1, le=100)] = 20
    ) -> List[Booking]:
        # AwareDatetime: "2026-12-01T10:00:00" without an offset is a 422, not a guess.
        # One bounded SELECT of the rows, not ids followed by one session.get() per id.
        return list(queries.recent_bookings(session, since, limit))

    return app


app = create_app()

The tests (60, all real; 16 marked sqlite_only): seed data, filters, pagination, aggregates, dates and time zones, relationship filters, bulk DML and cascades, and the HTTP API with query counts:

py
import datetime as dt
import os
from typing import Dict, Iterator

import pytest
from fastapi.testclient import TestClient
from sqlalchemy.engine import Engine
from sqlmodel import Session, SQLModel

from app.db import create_db_and_tables, make_engine
from app.main import create_app
from app.models import Amenity, Booking, Review, Room, User

D = dt.date
UTC = dt.timezone.utc
TEHRAN = dt.timezone(dt.timedelta(hours=3, minutes=30))


def seed(engine: Engine) -> Dict[str, int]:
    """Ids follow the order below. 6 rooms (one soft-deleted, two sharing a price), 3 amenities, 2 users, 5 bookings, 7 reviews."""
    with Session(engine) as s:
        wifi, balcony, kitchen = Amenity(name="wifi"), Amenity(name="balcony"), Amenity(name="kitchen")
        alice, bob = User(email="alice@example.com"), User(email="bob@example.com")
        garden = Room(name="Garden", city="Tabriz", capacity=2, price_cents=9000, amenities=[wifi])
        harbour = Room(
            name="Harbour Suite", city="Bandar Abbas", capacity=4, price_cents=20000, amenities=[wifi, balcony, kitchen]
        )
        loft = Room(name="Loft", city="Tabriz", capacity=3, price_cents=12000, amenities=[wifi, kitchen])
        studio = Room(name="Studio", city="Shiraz", capacity=1, price_cents=6000)
        courtyard = Room(name="Courtyard", city="Shiraz", capacity=2, price_cents=9000, amenities=[balcony])
        attic = Room(
            name="Attic", city="Tabriz", capacity=1, price_cents=5000, deleted_at=dt.datetime(2026, 11, 1, tzinfo=UTC)
        )
        # flush one by one so the ids follow this order: in one add_all batch with amenities
        # attached, the Courtyard got id 3 instead of 5 (observed on SQLAlchemy 2.0.58)
        for obj in (garden, harbour, loft, studio, courtyard, attic, alice, bob):
            s.add(obj)
            s.flush()
        bookings = [  # keyword arguments: no Booking object exists before it is added
            dict(room=garden, user=alice, start_date=D(2026, 12, 1), end_date=D(2026, 12, 4),
                 created_at=dt.datetime(2026, 11, 20, 9, 0, tzinfo=UTC)),
            dict(room=garden, user=bob, start_date=D(2026, 12, 10), end_date=D(2026, 12, 12),
                 created_at=dt.datetime(2026, 11, 21, 9, 0, tzinfo=UTC)),
            dict(room=harbour, user=alice, start_date=D(2026, 12, 2), end_date=D(2026, 12, 5), guests=3,
                 created_at=dt.datetime(2026, 11, 22, 13, 30, tzinfo=TEHRAN)),  # = 10:00 UTC
            dict(room=loft, start_date=D(2026, 12, 20), end_date=D(2026, 12, 22),
                 created_at=dt.datetime(2026, 11, 23, 9, 0, tzinfo=UTC)),
            dict(room=courtyard, user=bob, start_date=D(2026, 12, 3), end_date=D(2026, 12, 6),
                 created_at=dt.datetime(2026, 11, 24, 9, 0, tzinfo=UTC)),
        ]
        for kw in bookings:
            s.add(Booking(**kw))  # type: ignore[arg-type]
            s.flush()
        s.add_all(
            [Review(room=garden, rating=r) for r in (5, 4)]
            + [Review(room=harbour, rating=r) for r in (5, 5, 3)]
            + [Review(room=loft, rating=2), Review(room=courtyard, rating=4)]
        )
        s.commit()
        ids = {r.name: r.id for r in (garden, harbour, loft, studio, courtyard, attic)}
        ids.update(alice=alice.id, bob=bob.id, wifi=wifi.id, balcony=balcony.id, kitchen=kitchen.id)
        return ids  # type: ignore[return-value]


# TEST_DATABASE_URL selects the backend; default is in-memory SQLite (the only one run here).
# e.g. TEST_DATABASE_URL=postgresql+psycopg://app:app@localhost:5432/rooms_test pytest -m "not sqlite_only"
DATABASE_URL = os.environ.get("TEST_DATABASE_URL", "sqlite://")
IS_SQLITE = DATABASE_URL.startswith("sqlite")


def pytest_collection_modifyitems(config, items):  # type: ignore[no-untyped-def]
    """Tests marked sqlite_only assert SQLite's SQL text, plans or storage: skip them elsewhere."""
    if IS_SQLITE:
        return
    skip = pytest.mark.skip(reason="asserts SQLite-specific SQL text or behaviour")
    for item in items:
        if "sqlite_only" in item.keywords:
            item.add_marker(skip)


@pytest.fixture
def engine() -> Iterator[Engine]:
    eng = make_engine(DATABASE_URL)
    create_db_and_tables(eng)
    yield eng
    SQLModel.metadata.drop_all(eng)  # a server database outlives the test
    eng.dispose()


@pytest.fixture
def ids(engine: Engine) -> Dict[str, int]:
    return seed(engine)


@pytest.fixture
def session(engine: Engine, ids: Dict[str, int]) -> Iterator[Session]:
    with Session(engine) as s:
        yield s


@pytest.fixture
def client(engine: Engine, ids: Dict[str, int]) -> Iterator[TestClient]:
    with TestClient(create_app(engine=engine)) as c:
        yield c
py
import datetime as dt

import pytest
from pydantic import ValidationError
from sqlmodel import Session, select

from app.filters import RoomFilter, apply_room_filter, room_order
from app.models import Room
from app.querycount import count_queries


def names(session: Session, **kw: object) -> list:
    f = RoomFilter(**kw)  # type: ignore[arg-type]
    stmt = apply_room_filter(select(Room.name), f).order_by(*room_order(f.sort))
    return list(session.exec(stmt).all())


def test_no_filter_hides_soft_deleted_and_sorts_by_price_then_id(session: Session) -> None:
    # Garden and Courtyard both cost 9000: the id tie-breaker puts Garden (id 1) first.
    assert names(session) == ["Studio", "Garden", "Courtyard", "Loft", "Harbour Suite"]
    assert names(session, include_deleted=True)[0] == "Attic"


def test_q_matches_name_or_city_case_insensitively(session: Session) -> None:
    assert names(session, q="tabriz") == ["Garden", "Loft"]
    assert names(session, q="SUITE") == ["Harbour Suite"]


@pytest.mark.sqlite_only
def test_q_wildcards_are_escaped(session: Session, engine) -> None:  # type: ignore[no-untyped-def]
    with count_queries(engine) as log:
        assert names(session, q="%") == []  # a literal percent sign, not "match everything"
    assert "ESCAPE '/'" in log.statements[0]
    assert "lower(room.name) LIKE '%' || lower(?) || '%' ESCAPE '/'" in log.statements[0]
    assert log.entries[0][1][0] == "/%"  # the user's % escaped with /


@pytest.mark.sqlite_only
def test_in_and_not(session: Session, engine) -> None:  # type: ignore[no-untyped-def]
    with count_queries(engine) as log:
        assert names(session, city=["Shiraz", "Bandar Abbas"]) == ["Studio", "Courtyard", "Harbour Suite"]
    assert "room.city IN (?, ?)" in log.statements[0]
    assert names(session, exclude_city="Tabriz") == ["Studio", "Courtyard", "Harbour Suite"]


def test_capacity_and_price(session: Session) -> None:
    assert names(session, min_capacity=2, max_price=12000) == ["Garden", "Courtyard", "Loft"]


@pytest.mark.sqlite_only
def test_every_listed_amenity_is_required(session: Session, engine) -> None:  # type: ignore[no-untyped-def]
    with count_queries(engine) as log:
        assert names(session, amenity=["wifi", "kitchen"]) == ["Loft", "Harbour Suite"]
    assert log.statements[0].count("EXISTS (SELECT 1 FROM amenity, roomamenitylink") == 2


def test_availability_excludes_overlapping_bookings(session: Session) -> None:
    # Dec 3-4 clashes with Garden [1,4), Harbour [2,5), Courtyard [3,6)
    got = names(session, available_from=dt.date(2026, 12, 3), available_to=dt.date(2026, 12, 4))
    assert got == ["Studio", "Loft"]


@pytest.mark.sqlite_only
def test_sort_by_rating_puts_unrated_last(session: Session, engine) -> None:  # type: ignore[no-untyped-def]
    with count_queries(engine) as log:
        got = names(session, sort="rating")
    # Garden 4.5, Harbour 4.33, Courtyard 4.0, Loft 2.0, Studio no reviews
    assert got == ["Garden", "Harbour Suite", "Courtyard", "Loft", "Studio"]
    assert "DESC NULLS LAST" in log.statements[0]
    assert names(session, sort="-price")[0] == "Harbour Suite"


def test_filter_model_validation() -> None:
    with pytest.raises(ValidationError, match="go together"):
        RoomFilter(available_from=dt.date(2026, 12, 1))
    with pytest.raises(ValidationError, match="must be after"):
        RoomFilter(available_from=dt.date(2026, 12, 2), available_to=dt.date(2026, 12, 1))
    with pytest.raises(ValidationError, match="Extra inputs are not permitted"):
        RoomFilter(capactiy=2)  # type: ignore[call-arg]
    with pytest.raises(ValidationError):
        RoomFilter(sort="price; DROP TABLE room")  # type: ignore[arg-type]


def test_all_values_are_bound_parameters(session: Session, engine) -> None:  # type: ignore[no-untyped-def]
    evil = "x' OR '1'='1"
    with count_queries(engine) as log:
        assert names(session, q=evil) == []
    assert evil not in log.statements[0]
py
from typing import Dict, List

import pytest
from sqlmodel import Session, select

from app.models import Room
from app.pagination import decode_cursor, encode_cursor, paginate_keyset, paginate_offset
from app.querycount import count_queries

LIVE = select(Room).where(Room.deleted_at == None)  # noqa: E711


def walk_offset(session: Session, limit: int) -> List[List[str]]:
    pages, offset = [], 0
    while True:
        items, total = paginate_offset(session, LIVE.order_by(Room.price_cents, Room.id), limit=limit, offset=offset)
        if not items:
            return pages
        pages.append([r.name for r in items])
        offset += limit


def walk_keyset(session: Session, limit: int, row_values: bool = False) -> List[List[str]]:
    pages, cursor = [], None
    while True:
        items, cursor = paginate_keyset(session, LIVE, limit=limit, cursor=cursor, row_values=row_values)
        pages.append([r.name for r in items])
        if cursor is None:
            return pages


def test_offset_and_keyset_agree_on_a_static_table(session: Session) -> None:
    expected = [["Studio", "Garden"], ["Courtyard", "Loft"], ["Harbour Suite"]]
    assert walk_offset(session, 2) == expected
    assert walk_keyset(session, 2) == expected
    assert walk_keyset(session, 2, row_values=True) == expected


@pytest.mark.sqlite_only
def test_offset_envelope_total_ignores_limit(session: Session, engine) -> None:  # type: ignore[no-untyped-def]
    with count_queries(engine) as log:
        items, total = paginate_offset(session, LIVE.order_by(Room.price_cents, Room.id), limit=2, offset=2)
    assert total == 5 and [r.name for r in items] == ["Courtyard", "Loft"]
    assert log.count == 2
    assert log.statements[0].startswith("SELECT count(*) AS count_1 FROM (SELECT room.name")
    assert "ORDER BY" not in log.statements[0]  # the count drops the ORDER BY
    assert log.statements[1].endswith("ORDER BY room.price_cents, room.id LIMIT ? OFFSET ?")


@pytest.mark.sqlite_only
def test_keyset_sql_is_a_seek_predicate(session: Session, engine, ids: Dict[str, int]) -> None:  # type: ignore[no-untyped-def]
    with count_queries(engine) as log:
        paginate_keyset(session, LIVE, limit=2, cursor=encode_cursor(9000, ids["Garden"]))
        paginate_keyset(session, LIVE, limit=2, cursor=encode_cursor(9000, ids["Garden"]), row_values=True)
    assert "room.price_cents >= ? AND (room.price_cents > ? OR room.price_cents = ? AND room.id > ?)" in log.statements[0]
    assert log.statements[0].endswith("ORDER BY room.price_cents, room.id LIMIT ? OFFSET ?")
    assert log.entries[0][1][-2:] == (3, 0)  # limit + 1; SQLite renders OFFSET 0 with every LIMIT
    assert "(room.price_cents, room.id) > (?, ?)" in log.statements[1]


def test_insert_between_pages_duplicates_with_offset_not_with_keyset(session: Session) -> None:
    stmt = LIVE.order_by(Room.price_cents, Room.id)
    page1, _ = paginate_offset(session, stmt, limit=2, offset=0)
    k1, cursor = paginate_keyset(session, LIVE, limit=2, cursor=None)
    assert [r.name for r in page1] == [r.name for r in k1] == ["Studio", "Garden"]

    session.add(Room(name="Hostel Bed", city="Shiraz", capacity=1, price_cents=3000))  # sorts first
    session.commit()

    page2, _ = paginate_offset(session, stmt, limit=2, offset=2)
    k2, _ = paginate_keyset(session, LIVE, limit=2, cursor=cursor)
    assert [r.name for r in page2] == ["Garden", "Courtyard"]  # Garden shown twice
    assert [r.name for r in k2] == ["Courtyard", "Loft"]  # continues after Garden


def test_delete_between_pages_skips_with_offset(session: Session, ids: Dict[str, int]) -> None:
    stmt = LIVE.order_by(Room.price_cents, Room.id)
    page1, _ = paginate_offset(session, stmt, limit=2, offset=0)
    _, cursor = paginate_keyset(session, LIVE, limit=2, cursor=None)
    session.delete(session.get(Room, ids["Studio"]))
    session.commit()
    page2, _ = paginate_offset(session, stmt, limit=2, offset=2)
    k2, _ = paginate_keyset(session, LIVE, limit=2, cursor=cursor)
    assert [r.name for r in page2] == ["Loft", "Harbour Suite"]  # Courtyard never shown
    assert [r.name for r in k2] == ["Courtyard", "Loft"]


def test_keyset_repeats_a_row_when_its_sort_key_changes(session: Session, ids: Dict[str, int]) -> None:
    """Keyset is stable under inserts/deletes, NOT under updates of the sort key itself."""
    k1, cursor = paginate_keyset(session, LIVE, limit=2, cursor=None)
    assert [r.name for r in k1] == ["Studio", "Garden"]  # page 1 ends at (9000, Garden)
    studio = session.get(Room, ids["Studio"])
    studio.price_cents = 10000  # type: ignore[union-attr]  # already shown, now sorts after the cursor
    session.commit()
    k2, _ = paginate_keyset(session, LIVE, limit=3, cursor=cursor)
    assert [r.name for r in k2] == ["Courtyard", "Studio", "Loft"]  # Studio shown a second time


def test_cursor_round_trip_and_tampering() -> None:
    assert decode_cursor(encode_cursor(9000, 1)) == (9000, 1)
    huge = encode_cursor(10**100, 1)  # valid JSON ints, far outside INTEGER
    for bad in ("not-base64!", encode_cursor(1, 1)[:-2] + "zz", "W1wiYVwiXV0", huge, encode_cursor(True, 1)):
        with pytest.raises(ValueError, match="invalid cursor"):
            decode_cursor(bad)
py
from typing import Dict

import pytest

from sqlmodel import Session

from app import queries
from app.querycount import count_queries


@pytest.mark.sqlite_only
def test_exists_count_len_same_answer_different_sql(session: Session, engine, ids: Dict[str, int]) -> None:  # type: ignore[no-untyped-def]
    g = ids["Garden"]
    with count_queries(engine) as log:
        assert queries.has_bookings_exists(session, g) is True
        assert queries.count_bookings(session, g) == 2
        assert queries.count_bookings_with_len(session, g) == 2
        assert queries.has_bookings_exists(session, ids["Studio"]) is False
    exists_sql, count_sql, len_sql, _ = log.statements
    assert exists_sql == "SELECT EXISTS (SELECT * FROM booking WHERE booking.room_id = ?) AS anon_1"
    assert count_sql == "SELECT count(*) AS count_1 FROM booking WHERE booking.room_id = ?"
    assert len_sql.startswith("SELECT booking.id, booking.room_id, booking.user_id, booking.start_date")


@pytest.mark.sqlite_only
def test_correlated_scalar_subquery_column(session: Session, engine) -> None:  # type: ignore[no-untyped-def]
    with count_queries(engine) as log:
        rows = dict(queries.rooms_with_avg_rating(session))
    assert rows == {"Garden": 4.5, "Harbour Suite": 4.33, "Loft": 2.0, "Studio": None, "Courtyard": 4.0, "Attic": None}
    assert log.statements[0] == (
        "SELECT room.name, (SELECT avg(review.rating) AS avg_1 FROM review WHERE review.room_id = room.id) "
        "AS avg_rating FROM room ORDER BY room.id"
    )


def test_outer_join_keeps_zero_rows_inner_join_drops_them(session: Session) -> None:
    outer = queries.booking_counts_outerjoin(session)
    inner = queries.booking_counts_innerjoin(session)
    assert outer == [("Garden", 2), ("Courtyard", 1), ("Harbour Suite", 1), ("Loft", 1), ("Attic", 0), ("Studio", 0)]
    assert inner == outer[:4]


@pytest.mark.sqlite_only
def test_group_by_having_with_labels(session: Session, engine) -> None:  # type: ignore[no-untyped-def]
    with count_queries(engine) as log:
        got = queries.city_stats(session, min_rooms=2)
    assert got == [("Shiraz", 2, 7500.0, 6000, 9000), ("Tabriz", 2, 10500.0, 9000, 12000)]
    sql = log.statements[0]
    assert "GROUP BY room.city HAVING count(room.id) >= ? ORDER BY rooms DESC, room.city" in sql
    assert queries.city_stats(session, min_rooms=1)[-1][0] == "Bandar Abbas"


def test_text_with_bound_parameter_vs_fstring_injection(session: Session) -> None:
    evil = "' OR 1=1 --"
    assert queries.search_names_text(session, evil) == []
    leaked = queries.search_names_fstring(session, evil)
    assert len(leaked) == 6  # every room, including the soft-deleted one
    assert queries.search_names_text(session, "our") == ["Courtyard", "Harbour Suite"]
py
import datetime as dt
from typing import Dict

import pytest
from sqlalchemy import Column, DateTime, Integer, MetaData, Table, insert, select
from sqlalchemy.exc import StatementError
from sqlmodel import Session

from app import queries
from app.models import Booking, Room

D = dt.date
UTC = dt.timezone.utc
TEHRAN = dt.timezone(dt.timedelta(hours=3, minutes=30))


@pytest.mark.parametrize(
    "start,end,free",
    [
        (D(2026, 12, 3), D(2026, 12, 5), False),  # partial overlap with [1, 4)
        (D(2026, 12, 4), D(2026, 12, 10), True),  # back to back on both sides
        (D(2026, 11, 28), D(2026, 12, 15), False),  # contains both bookings
        (D(2026, 12, 2), D(2026, 12, 3), False),  # inside the first
        (D(2026, 11, 29), D(2026, 12, 1), True),  # ends the day the first starts
    ],
)
def test_overlap_boundaries(session: Session, ids: Dict[str, int], start: dt.date, end: dt.date, free: bool) -> None:
    assert queries.room_is_free(session, ids["Garden"], start, end) is free


def test_between_is_inclusive_on_both_ends(session: Session) -> None:
    # start dates: Dec 1, 10, 2, 20, 3 (ids 1..5)
    assert queries.bookings_starting_between(session, D(2026, 12, 1), D(2026, 12, 3)) == [1, 3, 5]
    assert queries.bookings_starting_between(session, D(2026, 12, 3), D(2026, 12, 10)) == [2, 5]


@pytest.mark.sqlite_only
def test_aware_datetimes_are_stored_in_utc(session: Session, engine) -> None:  # type: ignore[no-untyped-def]
    b = session.get(Booking, 3)
    assert b is not None
    assert b.created_at == dt.datetime(2026, 11, 22, 10, 0, tzinfo=UTC)
    with engine.connect() as conn:
        raw = conn.exec_driver_sql("SELECT created_at FROM booking WHERE id = 3").scalar()
    assert raw == "2026-11-22 10:00:00.000000"
    # the same instant written with any offset finds the same rows
    since_tehran = dt.datetime(2026, 11, 22, 13, 30, tzinfo=TEHRAN)
    since_utc = dt.datetime(2026, 11, 22, 10, 0, tzinfo=UTC)
    assert queries.bookings_created_since(session, since_tehran) == [3, 4, 5]
    assert queries.bookings_created_since(session, since_utc) == [3, 4, 5]


def test_naive_datetime_is_rejected(session: Session) -> None:
    with pytest.raises(StatementError, match="naive datetime"):
        queries.bookings_created_since(session, dt.datetime(2026, 11, 22, 10, 0))


@pytest.mark.sqlite_only
def test_plain_datetime_timezone_true_drops_the_offset_on_sqlite(engine) -> None:  # type: ignore[no-untyped-def]
    md = MetaData()
    t = Table("plain_ts", md, Column("id", Integer, primary_key=True), Column("at", DateTime(timezone=True)))
    md.create_all(engine)
    with engine.begin() as conn:
        conn.execute(insert(t).values(id=1, at=dt.datetime(2026, 11, 22, 13, 30, tzinfo=TEHRAN)))
        back = conn.execute(select(t.c.at)).scalar()
        raw = conn.exec_driver_sql("SELECT at FROM plain_ts").scalar()
    assert raw == "2026-11-22 13:30:00.000000"  # offset silently gone, not converted
    assert back == dt.datetime(2026, 11, 22, 13, 30) and back.tzinfo is None
py
from typing import Dict

import pytest

from sqlmodel import Session

from app import queries
from app.models import Amenity
from app.querycount import count_queries


@pytest.mark.sqlite_only
def test_any_on_a_many_to_many(session: Session, engine) -> None:  # type: ignore[no-untyped-def]
    with count_queries(engine) as log:
        assert queries.rooms_with_amenity(session, "balcony") == ["Courtyard", "Harbour Suite"]
    assert log.statements[0] == (
        "SELECT room.name FROM room WHERE EXISTS (SELECT 1 FROM amenity, roomamenitylink "
        "WHERE room.id = roomamenitylink.room_id AND amenity.id = roomamenitylink.amenity_id "
        "AND amenity.name = ?) ORDER BY room.name"
    )


def test_not_any_is_the_anti_join(session: Session) -> None:
    assert queries.rooms_without_bookings(session) == ["Attic", "Studio"]
    assert queries.users_with_bookings(session) == ["alice@example.com", "bob@example.com"]


@pytest.mark.sqlite_only
def test_has_on_a_many_to_one(session: Session, engine) -> None:  # type: ignore[no-untyped-def]
    with count_queries(engine) as log:
        assert queries.bookings_in_city(session, "Tabriz") == [1, 2, 4]
    assert "WHERE EXISTS (SELECT 1 FROM room WHERE room.id = booking.room_id AND room.city = ?)" in log.statements[0]


def test_contains_an_object(session: Session, ids: Dict[str, int]) -> None:
    kitchen = session.get(Amenity, ids["kitchen"])
    assert queries.rooms_containing(session, kitchen) == ["Harbour Suite", "Loft"]  # type: ignore[arg-type]


def test_join_filter_does_not_filter_the_loaded_collection(session: Session, ids: Dict[str, int]) -> None:
    rooms = queries.rooms_booked_by_join(session, ids["alice"])
    assert [r.name for r in rooms] == ["Garden", "Harbour Suite"]
    garden = rooms[0]
    # selectinload loads ALL bookings of Garden, including Bob's
    assert sorted(b.user_id for b in garden.bookings) == [ids["alice"], ids["bob"]]


def test_contains_eager_loads_only_the_filtered_rows(session: Session, ids: Dict[str, int], engine) -> None:  # type: ignore[no-untyped-def]
    with count_queries(engine) as log:
        rooms = queries.rooms_booked_contains_eager(session, ids["alice"])
        garden = rooms[0]
        assert [b.user_id for b in garden.bookings] == [ids["alice"]]
    assert log.count == 1  # one JOINed SELECT, no second query
py
import datetime as dt
from typing import Dict

import pytest
from sqlalchemy import event, func
from sqlalchemy.pool import StaticPool
from sqlmodel import Session, create_engine, select

from app import queries
from app.db import create_db_and_tables
from app.models import Booking, Review, Room, User
from app.querycount import count_queries
from app.softdelete import SoftDeleteSession
from tests.conftest import seed


def counts(session: Session) -> Dict[str, int]:
    return {
        m.__name__: session.exec(select(func.count()).select_from(m)).one()  # type: ignore[attr-defined]
        for m in (Room, Booking, Review)
    }


@pytest.mark.parametrize("sync,expected", [("auto", 9900), ("evaluate", 9900), ("fetch", 9900), (False, 9000)])
def test_bulk_update_and_synchronize_session(session: Session, ids: Dict[str, int], sync, expected) -> None:  # type: ignore[no-untyped-def]
    garden = session.get(Room, ids["Garden"])
    assert garden is not None and garden.price_cents == 9000
    assert queries.raise_prices(session, "Tabriz", 10, sync=sync) == 3  # Garden, Loft, Attic
    assert garden.price_cents == expected  # False: the loaded object is now stale
    session.commit()  # commit expires everything; the next read is fresh
    assert garden.price_cents == 9900


def test_batched_update_selects_bounded_ids_then_updates_them(session: Session, engine) -> None:  # type: ignore[no-untyped-def]
    assert not hasattr(queries.update(Room), "limit")  # no UPDATE ... LIMIT in SQLAlchemy 2.0
    with count_queries(engine) as log:
        sizes = queries.raise_prices_in_batches(session, "Tabriz", 10, batch=2)
    assert sizes == [2, 1]  # Garden, Loft | Attic
    assert [r for r in session.exec(select(Room.price_cents).where(Room.city == "Tabriz").order_by(Room.id)).all()] == [9900, 13200, 5500]
    updates = [s for s in log.statements if s.startswith("UPDATE")]
    assert len(updates) == 2 and all(" IN (" in s for s in updates)
    assert any(s.endswith("ORDER BY room.id LIMIT ? OFFSET ?") for s in log.statements)


@pytest.mark.sqlite_only
def test_bulk_update_is_one_statement(session: Session, engine) -> None:  # type: ignore[no-untyped-def]
    with count_queries(engine) as log:
        queries.raise_prices(session, "Tabriz", 10, sync=False)
    assert log.statements == ["UPDATE room SET price_cents=((room.price_cents * ?) / ?) WHERE room.city = ?"]


def test_bulk_delete_runs_database_cascades_not_orm_cascades(session: Session, engine) -> None:  # type: ignore[no-untyped-def]
    with count_queries(engine) as log:
        assert queries.delete_rooms_in_city(session, "Tabriz") == 3
    session.commit()
    assert log.statements[-1] == "DELETE FROM room WHERE room.city = ?"
    assert not any(s.startswith("DELETE FROM booking") for s in log.statements)
    # ON DELETE CASCADE removed the 3 Tabriz bookings and the 3 Tabriz reviews anyway
    assert counts(session) == {"Room": 3, "Booking": 2, "Review": 4}


def test_session_delete_runs_the_orm_cascade(session: Session, engine, ids: Dict[str, int]) -> None:  # type: ignore[no-untyped-def]
    garden = session.get(Room, ids["Garden"])
    with count_queries(engine) as log:
        session.delete(garden)
        session.commit()
    # cascade_delete=True: bookings are loaded and deleted one by one by the ORM;
    # reviews (passive_deletes="all") are left to ON DELETE CASCADE; never SELECTed.
    stmts = log.statements
    assert any(s.startswith("SELECT booking.") for s in stmts)
    assert not any("FROM review" in s for s in stmts)
    assert sum(s.startswith("DELETE FROM booking") for s in stmts) == 1  # executemany of 2 rows
    assert counts(session) == {"Room": 5, "Booking": 3, "Review": 5}


def test_delete_user_sets_null(session: Session, ids: Dict[str, int]) -> None:
    session.delete(session.get(User, ids["bob"]))
    session.commit()
    assert session.exec(select(Booking.user_id).where(Booking.id == 2)).one() is None


@pytest.mark.sqlite_only
def test_without_foreign_keys_bulk_delete_leaves_orphans() -> None:
    eng = create_engine("sqlite://", poolclass=StaticPool, connect_args={"check_same_thread": False})
    create_db_and_tables(eng)  # no PRAGMA foreign_keys=ON listener on this engine
    seed(eng)
    with Session(eng) as s:
        queries.delete_rooms_in_city(s, "Tabriz")
        s.commit()
        assert counts(s) == {"Room": 3, "Booking": 5, "Review": 7}  # 3 bookings, 3 reviews orphaned


def test_soft_delete_session_hides_deleted_rooms(engine, ids: Dict[str, int]) -> None:  # type: ignore[no-untyped-def]
    with SoftDeleteSession(engine) as s:
        assert "Attic" not in s.exec(select(Room.name)).all()
        assert len(s.exec(select(Room)).all()) == 5
        everything = s.exec(select(Room).execution_options(include_deleted=True)).all()
        assert len(everything) == 6
        queries.soft_delete_room(s, s.get(Room, ids["Loft"]), dt.datetime(2026, 11, 29, tzinfo=dt.timezone.utc))  # type: ignore[arg-type]
        s.commit()
        assert sorted(s.exec(select(Room.name)).all()) == ["Courtyard", "Garden", "Harbour Suite", "Studio"]
py
from typing import Dict

import pytest

from fastapi.testclient import TestClient
from sqlmodel import Session

from app.models import Booking, Room
from app.pagination import encode_cursor
from app.querycount import count_queries


def test_list_envelope_and_filters(client: TestClient, engine) -> None:  # type: ignore[no-untyped-def]
    with count_queries(engine) as log:
        r = client.get("/rooms", params={"city": ["Tabriz", "Shiraz"], "limit": 2, "offset": 1})
    assert r.status_code == 200
    body = r.json()
    assert body["total"] == 4 and body["limit"] == 2 and body["offset"] == 1
    assert [i["name"] for i in body["items"]] == ["Garden", "Courtyard"]
    assert log.count == 2  # COUNT + page


def test_unknown_and_out_of_range_parameters_are_422(client: TestClient) -> None:
    r = client.get("/rooms", params={"capactiy": 2})
    assert r.status_code == 422 and r.json()["detail"][0]["type"] == "extra_forbidden"
    assert client.get("/rooms", params={"limit": 1000}).status_code == 422
    assert client.get("/rooms", params={"sort": "id; DROP TABLE room"}).status_code == 422
    assert client.get("/rooms", params={"available_from": "2026-12-01"}).status_code == 422


def test_amenity_and_availability_through_http(client: TestClient) -> None:
    r = client.get("/rooms", params={"amenity": ["wifi", "kitchen"], "sort": "-price"})
    assert [i["name"] for i in r.json()["items"]] == ["Harbour Suite", "Loft"]
    r = client.get("/rooms", params={"available_from": "2026-12-03", "available_to": "2026-12-04"})
    assert [i["name"] for i in r.json()["items"]] == ["Studio", "Loft"]


def test_cursor_feed_walk(client: TestClient, engine) -> None:  # type: ignore[no-untyped-def]
    seen, cursor, requests = [], None, 0
    with count_queries(engine) as log:
        while True:
            params = {"limit": 2} if cursor is None else {"limit": 2, "cursor": cursor}
            body = client.get("/rooms/feed", params=params).json()
            requests += 1
            seen += [i["name"] for i in body["items"]]
            cursor = body["next_cursor"]
            if cursor is None:
                break
    assert seen == ["Studio", "Garden", "Courtyard", "Loft", "Harbour Suite"]
    assert requests == 3 and log.count == 3  # one SELECT per page, no COUNT
    assert client.get("/rooms/feed", params={"cursor": "garbage"}).status_code == 400
    huge = encode_cursor(10**100, 1)  # before the bounds check: OverflowError in sqlite3 -> 500
    assert client.get("/rooms/feed", params={"cursor": huge}).status_code == 400


def test_list_endpoint_query_count_is_constant(client: TestClient, engine) -> None:  # type: ignore[no-untyped-def]
    with count_queries(engine) as small:
        r = client.get("/rooms/with-bookings", params={"limit": 2})
    with count_queries(engine) as big:
        r = client.get("/rooms/with-bookings", params={"limit": 100})
    assert len(r.json()) == 5
    assert small.count == big.count == 2  # page + one SELECT ... IN (...) for the bookings
    assert " IN (" in big.statements[1]


def test_free_endpoint(client: TestClient, ids: Dict[str, int]) -> None:
    g = ids["Garden"]
    assert client.get(f"/rooms/{g}/free", params={"start": "2026-12-04", "end": "2026-12-10"}).json() == {"free": True}
    assert client.get(f"/rooms/{g}/free", params={"start": "2026-12-03", "end": "2026-12-05"}).json() == {"free": False}
    assert client.get(f"/rooms/{g}/free", params={"start": "2026-12-05", "end": "2026-12-05"}).status_code == 422


def test_stats_endpoint(client: TestClient) -> None:
    assert client.get("/stats/cities").json() == [
        {"city": "Shiraz", "rooms": 2, "avg_price": 7500.0, "min_price": 6000, "max_price": 9000},
        {"city": "Tabriz", "rooms": 2, "avg_price": 10500.0, "min_price": 9000, "max_price": 12000},
    ]


def test_soft_delete_hides_from_lists(client: TestClient, ids: Dict[str, int], engine) -> None:  # type: ignore[no-untyped-def]
    assert client.delete(f"/rooms/{ids['Loft']}").status_code == 204
    assert client.delete(f"/rooms/{ids['Loft']}").status_code == 404
    names = [i["name"] for i in client.get("/rooms").json()["items"]]
    assert "Loft" not in names
    with Session(engine) as s:
        loft = s.get(Room, ids["Loft"])
        assert loft is not None and loft.deleted_at is not None and loft.deleted_at.tzinfo is not None
        assert s.get(Booking, 4) is not None  # soft delete keeps the history


@pytest.mark.sqlite_only
def test_aware_datetime_query_parameter(client: TestClient, engine) -> None:  # type: ignore[no-untyped-def]
    with count_queries(engine) as log:
        r = client.get("/bookings/recent", params={"since": "2026-11-22T13:30:00+03:30"})
    assert log.count == 1  # one bounded SELECT, not one get() per row
    assert log.statements[0].endswith("ORDER BY booking.created_at, booking.id LIMIT ? OFFSET ?")
    assert [b["id"] for b in r.json()] == [3, 4, 5]
    assert r.json()[0]["created_at"] == "2026-11-22T10:00:00Z"
    r = client.get("/bookings/recent", params={"since": "2026-11-22T10:00:00"})
    assert r.status_code == 422 and r.json()["detail"][0]["type"] == "timezone_aware"

The two scripts that produced the SQL and the query plans quoted in Mechanics, and the project file:

py
"""Print the SQL every recipe of the chapter sends: python -m app.echo_demo

echo=True logs each statement and its parameters through the `sqlalchemy.engine` logger.
"""

import datetime as dt

from sqlmodel import Session, select

from app import queries
from app.db import create_db_and_tables, make_engine
from app.filters import RoomFilter, apply_room_filter, room_order
from app.models import Room
from app.pagination import encode_cursor, paginate_keyset, paginate_offset


def step(title: str) -> None:
    print(f"\n-- {title}", flush=True)


def main() -> None:
    engine = make_engine("sqlite://")
    create_db_and_tables(engine)
    from tests.conftest import seed  # the same data the tests use

    ids = seed(engine)
    engine.echo = True
    with Session(engine) as s:
        step("1. filter model -> WHERE (q, city IN, min_capacity, amenity ANY, availability NOT EXISTS)")
        f = RoomFilter(
            q="a", city=["Tabriz", "Shiraz"], min_capacity=2, amenity=["wifi"],
            available_from=dt.date(2026, 12, 4), available_to=dt.date(2026, 12, 6),
        )
        stmt = apply_room_filter(select(Room), f).order_by(*room_order(f.sort))
        step("2. offset page: COUNT over the filtered query, then LIMIT/OFFSET")
        paginate_offset(s, stmt, limit=20, offset=0)
        step("3. keyset page after (9000, Garden)")
        paginate_keyset(s, select(Room).where(Room.deleted_at == None), limit=2,  # noqa: E711
                        cursor=encode_cursor(9000, ids["Garden"]))
        step("4. sort=rating: correlated scalar subquery, DESC NULLS LAST")
        s.exec(apply_room_filter(select(Room.name), RoomFilter(sort="rating")).order_by(*room_order("rating"))).all()
        step("5. exists vs count vs len")
        queries.has_bookings_exists(s, ids["Garden"])
        queries.count_bookings(s, ids["Garden"])
        queries.count_bookings_with_len(s, ids["Garden"])
        step("6. GROUP BY / HAVING with labels")
        queries.city_stats(s, 2)
        step("7. LEFT OUTER JOIN + count")
        queries.booking_counts_outerjoin(s)
        step("8. any() / has()")
        queries.rooms_with_amenity(s, "balcony")
        queries.bookings_in_city(s, "Tabriz")
        step("9. bulk UPDATE with synchronize_session='auto' (evaluate) and 'fetch'")
        queries.raise_prices(s, "Tabriz", 10)
        queries.raise_prices(s, "Shiraz", 5, sync="fetch")
        s.rollback()
        step("10. session.delete(room): ORM cascade for bookings, ON DELETE CASCADE for reviews")
        s.delete(s.get(Room, ids["Garden"]))
        s.commit()
        step("11. bulk DELETE: only the database cascades")
        queries.delete_rooms_in_city(s, "Shiraz")
        s.commit()
        step("12. text() with a bound parameter")
        queries.search_names_text(s, "our")


if __name__ == "__main__":
    main()
py
"""EXPLAIN QUERY PLAN and timings for offset vs keyset pages: python -m app.explain_demo [rows]

Builds an in-memory SQLite database with `rows` rooms (default 200,000), then prints the plan
of each statement the chapter discusses, and the median time of OFFSET vs keyset at
several depths. Numbers are from one laptop; the shape matters, not the milliseconds.
"""

import random
import statistics
import sys
import time
from typing import Any, List

from sqlalchemy import Index, func, insert, select as sa_select
from sqlalchemy.engine import Connection
from sqlmodel import col, select

from app.db import create_db_and_tables, make_engine
from app.models import Amenity, Booking, Room
from app.pagination import after_key, after_key_naive, after_key_row_value
from app.queries import overlaps

import datetime as dt


def plan(conn: Connection, title: str, stmt: Any) -> None:
    compiled = stmt.compile(dialect=conn.dialect)
    params = [compiled.params[k] for k in (compiled.positiontup or [])]
    sql = " ".join(str(compiled).split())
    rows = conn.exec_driver_sql("EXPLAIN QUERY PLAN " + sql, tuple(params)).all()
    print(f"\n-- {title}\n{sql}")
    for row in rows:  # (id, parent, notused, detail)
        print(f"   {row[0]:>3} {row[1]:>3}  {row[3]}")


def timed(conn: Connection, stmt: Any, repeat: int = 7) -> float:
    samples: List[float] = []
    for _ in range(repeat):
        t0 = time.perf_counter()
        conn.execute(stmt).all()
        samples.append((time.perf_counter() - t0) * 1000)
    return statistics.median(samples)


def main(n: int) -> None:
    engine = make_engine("sqlite://")
    create_db_and_tables(engine)
    rnd = random.Random(42)
    with engine.begin() as conn:
        conn.execute(
            insert(Room),
            [dict(name=f"room-{i}", city=rnd.choice(["Tabriz", "Shiraz", "Yazd", "Rasht"]),
                  capacity=rnd.randint(1, 6), price_cents=rnd.randint(30, 400) * 100) for i in range(n)],
        )
        conn.execute(
            insert(Booking),
            [dict(room_id=rnd.randint(1, n), start_date=dt.date(2026, 12, 1) + dt.timedelta(days=d),
                  end_date=dt.date(2026, 12, 1) + dt.timedelta(days=d + 2),
                  created_at=dt.datetime(2026, 11, 1, tzinfo=dt.timezone.utc)) for d in range(0, 2000)],
        )
        conn.exec_driver_sql("ANALYZE")

    page = select(Room).order_by(col(Room.price_cents), col(Room.id)).limit(20)
    with engine.connect() as conn:
        print(f"sqlite {conn.exec_driver_sql('select sqlite_version()').scalar()}, {n} rooms")
        plan(conn, "offset page, index on (price_cents, id)", page.offset(n - 1000))
        plan(conn, "keyset page, OR/AND seek predicate", page.where(after_key_naive(20000, n // 2)))
        plan(conn, "keyset page, OR/AND plus a leading >= bound", page.where(after_key(20000, n // 2)))
        plan(conn, "keyset page, row-value seek predicate", page.where(after_key_row_value(20000, n // 2)))
        plan(conn, "ORDER BY a column with no index", select(Room).order_by(col(Room.city), col(Room.id)).limit(20))
        plan(conn, "covering index: only indexed columns selected",
             sa_select(Room.id, Room.price_cents).where(Room.price_cents > 39000))
        plan(conn, "count(*)", sa_select(func.count()).select_from(Room))
        plan(conn, "overlap check for one room, index on (room_id, start_date)",
             sa_select(Booking.id).where(Booking.room_id == 7, overlaps(dt.date(2026, 12, 3), dt.date(2026, 12, 5))))
        plan(conn, "amenity any(): correlated EXISTS",
             select(Room.id).where(col(Room.amenities).any(Amenity.name == "wifi")).limit(20))

        print("\n-- median ms of 7 runs: OFFSET vs keyset at the same depth")
        keys = conn.execute(sa_select(Room.price_cents, Room.id).order_by(Room.price_cents, Room.id)).all()
        for depth in (0, 1_000, 50_000, n - 1_000):
            off = timed(conn, page.offset(depth))
            p, i = keys[depth - 1] if depth else (-1, -1)
            key = timed(conn, page.where(after_key_row_value(p, i)))
            naive = timed(conn, page.where(after_key_naive(p, i)))
            print(f"   depth {depth:>7}: offset {off:7.2f} ms   keyset {key:6.2f} ms   keyset-naive-OR {naive:6.2f} ms")

    # Same offset page without the composite index: the sort has to happen per query.
    with engine.begin() as conn:
        Index("ix_room_price_id", Room.price_cents, Room.id).drop(conn)
    with engine.connect() as conn:
        plan(conn, "offset page WITHOUT the (price_cents, id) index", page.offset(n - 1000))
        print(f"   depth {n - 1000:>7}: offset {timed(conn, page.offset(n - 1000)):7.2f} ms (no index)")


if __name__ == "__main__":
    main(int(sys.argv[1]) if len(sys.argv) > 1 else 200_000)
toml
[project]
name = "queries-pagination-aggregation"
version = "0.1.0"
description = "Snippets for the Queries in Practice chapter: filter models, offset and keyset pagination, exists, counts, aggregates, date ranges, cascade rules, query counts"
# The page targets Python 3.12+; the pins below are the newest releases that still install on 3.9,
# the only interpreter on the build machine (same pins as the SQLAlchemy & SQLModel chapter).
requires-python = ">=3.9"
dependencies = [
    "fastapi==0.128.8",
    "starlette==0.49.3",
    "pydantic==2.13.5",
    # 2.0.58 is the newest 2.0.x (maintenance series); 2.1.x needs Python 3.11.
    "sqlalchemy==2.0.58",
    # 0.0.34 is the last SQLModel release for Python 3.9 (0.0.35 dropped it).
    "sqlmodel==0.0.34",
    "uvicorn==0.39.0",
    # Lets Pydantic evaluate `str | None` annotations on Python 3.9; not needed on 3.10+.
    "eval-type-backport==0.4.0; python_version < '3.10'",
]

[project.optional-dependencies]
test = [
    "httpx==0.28.1",
    "pytest==8.4.2",
]

[build-system]
requires = ["setuptools>=61"]
build-backend = "setuptools.build_meta"

[tool.setuptools]
packages = ["app"]

[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-q -p no:cacheprovider"
markers = ["sqlite_only: asserts SQLite-rendered SQL, plans or storage; skipped when TEST_DATABASE_URL is not SQLite"]
pythonpath = ["."]

The Python angle ​

Three Python features carry this chapter. Operator overloading: Room.capacity >= 2 is not a boolean but a SQL expression, &, | and ~ build AND, OR and NOT, and tuple_(a, b) > tuple_(x, y) builds a row-value comparison. Python's own and, or and not cannot be overloaded, so they must never appear between column expressions. Generics in Pydantic: class Page(BaseModel, Generic[T]) makes one envelope type for every resource, and Page[RoomPublic] is a concrete model FastAPI documents in OpenAPI. Aware datetimes: datetime.now(timezone.utc) is an instant, datetime.now() is a wall-clock reading with no zone, and comparing the two raises TypeError in Python. The database layer must therefore never mix them, which is what UTCDateTime enforces. The SQLModel helper col() exists only for type checkers: col(Room.amenities).any(...) tells mypy that the attribute is an instrumented column or relationship, not a plain list.

The concept catalogue ​

GET /rooms?q=tab&city=Tabriz&city=Shiraz&amenity=wifi&min_capacity=2&limit=201. Query stringrepeated keys becomelists: city=[...]unknown key: 422 (extra="forbid")2. RoomFilterAnnotated[RoomFilter, Query()]types, bounds, Literalsort, model_validator3. apply_room_filterone condition per fieldand_(*conditions)icontains(autoescape)any() per amenity4. SQL + parametersWHERE ... IN (?, ?)EXISTS (SELECT 1 ...)values only as ? never in the SQL textThen two statements for an offset page: SELECT count(*) FROM (filtered query without ORDER BY), then the page withORDER BY price_cents, id LIMIT ? OFFSET ?; or one statement for a keyset page with limit + 1 rows.Response envelope: {items, total, limit, offset} or {items, next_cursor, limit}.

Filtering: where, and_, or_, not_, in_, is_ Must-know ​

In plain words: select(Room).where(cond1, cond2) keeps the rows for which every condition is true. Conditions are built from columns with Python operators: Room.capacity >= 2, col(Room.city).in_([...]), col(Room.deleted_at).is_(None). and_(), or_() and not_() (or &, |, ~) combine them. A filter function collects conditions in a list and passes and_(*conditions) once.

Common misunderstanding: "if f.city: stmt = stmt.where(Room.city == f.city[0] or f.city[1])." Python's or evaluates the truth of the first expression and returns one of the two objects, so the SQL silently compares with one city. Use or_() or in_(). Second: "Room.deleted_at == None and is_(None) are different." Both render IS NULL; linters flag == None, so the snippet uses col(Room.deleted_at).is_(None) in filter code and keeps == None # noqa: E711 in one place to show it. Third: in_([]) with an empty list is not an error. It renders a post-compile placeholder that SQLAlchemy expands to IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1) and returns no rows (real, runs/operators.txt).

Definition: where(*clauses) adds clauses joined by AND to the statement's WHERE. and_(*clauses), or_(*clauses) and not_(clause) build boolean expressions, ColumnOperators.in_(values) renders IN (?, ?, ...) with one bound parameter per value, is_(None) renders IS NULL and is_not(None) renders IS NOT NULL. Each call returns a new statement, so a function can extend a base query step by step.

     RoomFilter(city=["Tabriz", "Shiraz"], min_capacity=2, exclude_city=None)     (real, test_filters)
1    conditions = [room.deleted_at IS NULL]                 include_deleted=False
2    conditions += [room.city IN (?, ?)]                    params ('Tabriz', 'Shiraz')
3    conditions += [room.capacity >= ?]                     params (2,)
4    stmt.where(and_(*conditions))                          WHERE room.deleted_at IS NULL AND room.city IN (?, ?) AND room.capacity >= ?
5    exclude_city="Tabriz" adds not_(Room.city == ?)       rendered as room.city != ?  (real, runs/operators.txt)

Real scenario: a hotel search with optional city, capacity and price; an admin list "only active users with a verified email"; "orders in status paid or shipped" (in_); "tickets without an assignee" (is_(None)); excluding a test tenant (not_).

PythonSQLNote
.where(a, b)WHERE a AND bseveral .where() calls also AND together
and_(*conds)a AND b AND cbuild the list, apply once
or_(a, b)(a OR b)parentheses are added for you
not_(a) / ~aNOT (a)not_(x == y) is printed x != y (real)
col(x).in_([1, 2])x IN (?, ?)one parameter per value (post-compile)
col(x).in_([])IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1)no rows, no error (real)
col(x).not_in([1, 2])(x NOT IN (?, ?)) (real)NOT IN with a NULL in the list returns nothing
col(x).is_(None)x IS NULL== None renders the same
col(x).is_not(None)x IS NOT NULL
col(x).between(a, b)x BETWEEN ? AND ?inclusive both ends (Date ranges)
Room.capacity >= f.min_capacityroom.capacity >= ?values are always bound parameters

Fix / how to use it: one function apply_room_filter(stmt, f) that appends a condition per set field and calls where(and_(*conditions)) once; in_() for lists; is_() for NULL checks; or_() only where the product really means OR (the text search over name or city).

In plain words: like("G%") matches a pattern where % is "any characters" and _ is "one character". ilike does the same ignoring case. contains(q) / icontains(q) wrap the value in %...% for you, and autoescape=True makes a % or _ typed by the user match literally.

Common misunderstanding: "col(Room.name).ilike(f"%{q}%") is safe because it is a bound parameter." It is safe from SQL injection, but not from wildcard injection: q="%" matches every row and q="_" matches every non-empty name. The snippet's icontains(q, autoescape=True) sends /% as the parameter with ESCAPE '/', so q="%" finds nothing (real, test_q_wildcards_are_escaped). Second: "ILIKE is case-insensitive everywhere." On SQLite, ilike renders lower(x) LIKE lower(?), and SQLite's lower() and LIKE only fold ASCII. The docs: "SQLite only understands upper/lower case for ASCII characters by default." Real: icontains("ün") does not find "Ünal Suite", icontains("Ün") does (runs/unicode-like.txt). PostgreSQL has native ILIKE and folds by locale (expected, not run).

Definition: ColumnOperators.like(pattern, escape=None), .ilike(...), .contains(other, autoescape=False), .icontains(...), .startswith(...), .endswith(...). With autoescape=True, SQLAlchemy escapes %, _ and the escape character / inside the value and adds ESCAPE '/'.

     q = "%"  (a user typing a percent sign)                                     (real)
1    ilike(f"%{q}%")                  pattern '%%%'           -> matches every room
2    icontains(q, autoescape=True)    '%' || lower(?) || '%' ESCAPE '/'  params ('/%', '/%')
3                                     -> matches only names that contain a literal %  -> []
     SQL: (lower(room.name) LIKE '%' || lower(?) || '%' ESCAPE '/') OR (lower(room.city) LIKE '%' || lower(?) || '%' ESCAPE '/')

Real scenario: a search box over room names; an admin "email contains" filter; autocomplete with startswith; product SKUs that contain underscores (AB_12), where an unescaped _ matches ABX12 too.

OperatorSQLite (real except FTS5)PostgreSQL (expected, not run)Index use
like("Gar%")room.name LIKE ?, ASCII case-insensitive by defaultcase-sensitiveprefix patterns can use a B-tree under conditions; %x% cannot
ilike("%x%")lower(room.name) LIKE lower(?)native ILIKEno plain B-tree; PostgreSQL pg_trgm GIN/GiST index ("trigram-based index searches for LIKE, ILIKE, ~, ~* and = queries")
contains(q)room.name LIKE '%' || ? || '%', a_b sent unescapedsameas %x%
icontains(q, autoescape=True)lower(...) LIKE '%' || lower(?) || '%' ESCAPE '/'ILIKE with escapeas %x%
startswith(q, autoescape=True)room.name LIKE ? || '%' ESCAPE '/', a_b sent as a/_bsamecan use an index
full-text searchFTS5 ("an SQLite virtual table module" for full-text search; not run)tsvector / tsquery + GINthe real answer for big text

Fix / how to use it: icontains(q, autoescape=True) for search boxes; limit q length in the filter model (max_length=50); for anything bigger than a few hundred thousand rows or for non-ASCII text, move to the database's full-text search (Indexing covers GIN and trigram indexes).

Filter models from query parameters: Query, Depends, extra="forbid" Must-know ​

In plain words: Instead of ten function parameters, declare a Pydantic model with the filter fields and write f: Annotated[RoomFilter, Query()]. FastAPI reads the query string into the model, Pydantic validates it (types, bounds, Literal choices, cross-field rules), and the route receives one object. Lists come from repeated keys: ?city=Tabriz&city=Shiraz.

Common misunderstanding: "extra="forbid" only looks at the model's fields." A query parameter model sees the whole query string. In the first version of the snippet, limit and offset were a separate Depends(paging) dependency, and GET /rooms?limit=2 answered 422 with extra_forbidden for limit and offset (real, found while writing the tests). The fix: put paging into the same model, as FastAPI's own example does (limit, offset, order_by, tags in one FilterParams). Second: "a sort string parameter is harmless." If it is interpolated into order_by(text(sort)) it is SQL injection. Make it a Literal["price", "-price", "name", "rating"] and map each value to columns in code, so ?sort=id; DROP TABLE room is a 422 (real, test_unknown_and_out_of_range_parameters_are_422).

Definition: FastAPI query parameter models: "This is supported since FastAPI version 0.115.0." The docs show model_config = {"extra": "forbid"} under "Forbid Extra Query Parameters", which makes an unknown parameter an error. The alternative is a class or function used with Depends() (a "Depends filter"): it can combine several dependencies and run code, but each field is a separate parameter. Pydantic's model_validator(mode="after") checks rules that involve two fields.

     GET /rooms?capactiy=2                                                     (real, curl-run.txt)
1    FastAPI collects query params     {"capactiy": "2"}
2    RoomFilter(extra="forbid")         unknown key
3    response                          422 {"detail":[{"type":"extra_forbidden","loc":["query","capactiy"],
                                            "msg":"Extra inputs are not permitted","input":"2"}]}
     GET /rooms?limit=1000             422 less_than_equal, "Input should be less than or equal to 100"
     GET /rooms?available_from=2026-12-01    422, model_validator: "available_from and available_to go together"

Real scenario: a typo in a mobile client (capactiy) that would silently return unfiltered results; a limit=1000000 scraping attempt; a date-range filter where only one date was sent; an admin UI that adds a new filter and the backend must document it in OpenAPI automatically.

ApproachExampleValidationOpenAPIUnknown params
Plain parametersdef f(city: List[str] = Query([]), ...)per parameteryesignored
Query parameter modelf: Annotated[RoomFilter, Query()]whole model + validatorsyes, flattenedignored, or 422 with extra="forbid"
Depends class/functionp: Annotated[Paging, Depends(paging)]per parameteryesignored
Model + extra="forbid" + separate DependsRoomFilter and paging together422 for the other dependency's params (real)
Raw request.query_paramsrequest.query_params.getlist("city")nonenoyour code

Fix / how to use it: one model per list endpoint with filters, sort and paging, extra="forbid", bounded numbers, Literal sort keys and a model_validator for pairs. Details of query and body models are in Request Validation; Depends patterns are in Dependency Injection.

Ordering: order_by, desc, nulls_last and the unique tie-breaker Must-know ​

In plain words: order_by(col(Room.price_cents), col(Room.id)) sorts by price and, among equal prices, by id. desc() reverses one column. nulls_last() decides where NULLs go. The last column must be unique, or the order of equal rows is undefined and pages can repeat or lose rows.

Common misunderstanding: "The database returns rows in insertion order." Without ORDER BY there is no order, and with ORDER BY price alone, two rooms at 9000 can swap between two requests. PostgreSQL warns: "The query optimizer takes LIMIT into account when generating query plans, so you are very likely to get different plans (yielding different row orders) depending on what you give for LIMIT and OFFSET." The seed has Garden and Courtyard both at 9000; the id tie-breaker always puts Garden (id 1) first (real). Second: "NULLs sort the same everywhere." SQLite: "SQLite considers NULL values to be smaller than any other values for sorting purposes." PostgreSQL: "By default, null values sort as if larger than any non-null value; that is, NULLS FIRST is the default for DESC order". So "best rated first" puts unrated rooms last on SQLite and first on PostgreSQL unless you write nulls_last().

Definition: Select.order_by(*clauses); ColumnElement.desc(), .asc(); nulls_last(clause) / nulls_first(clause) render NULLS LAST / NULLS FIRST; order_by(None) removes the ORDER BY (the count query uses it). An ORDER BY can be any expression, including a correlated scalar subquery.

     sort=rating  (real, test_sort_by_rating_puts_unrated_last)
1    ORDER BY (SELECT avg(review.rating) AS avg_1 FROM review WHERE review.room_id = room.id) DESC NULLS LAST, room.id
2    Garden 4.5  ->  Harbour Suite 4.33  ->  Courtyard 4.0  ->  Loft 2.0  ->  Studio (no reviews, NULL)
     sort=price
3    ORDER BY room.price_cents, room.id   ->  Studio 6000, Garden 9000 (id 1), Courtyard 9000 (id 5), Loft, Harbour

Real scenario: "cheapest first" with many rooms at the same price; "best rated" with new rooms that have no rating yet; "newest first" with created_at DESC, id DESC; a leaderboard where ties must be stable between page loads.

Sortorder_by(...)Index that serves it
price ascendingcol(Room.price_cents), col(Room.id)(price_cents, id)
price descendingcol(Room.price_cents).desc(), col(Room.id).desc()the same index, read backwards
namecol(Room.name)unique index on name (already unique, no tie-breaker needed)
rating, unrated lastnulls_last(avg_subquery.desc()), col(Room.id)none: computed per row (cache it in a column at scale)
mixed directionsprice ASC, id DESCneeds an index declared with those directions
randomfunc.random()none; full sort of all rows

Fix / how to use it: every list query ends its order_by with the primary key (or another unique column); sort keys come from a Literal and a mapping in code; use nulls_last()/nulls_first() explicitly when the column can be NULL; index the exact column list you sort by (Indexes behind ORDER BY).

Offset pagination: limit, offset and the envelope with total Must-know ​

In plain words: Page N with size L is .limit(L).offset((N - 1) * L). The response carries items, total, limit and offset, so the client can show "page 3 of 12" and jump to any page. The total is a second query, SELECT count(*) over the same filtered statement.

Common misunderstanding: "OFFSET skips rows cheaply." It produces them: "The rows skipped by an OFFSET clause still have to be computed inside the server; therefore a large OFFSET might be inefficient." Real numbers in Mechanics. Second: "the pages are stable." When a row is inserted before the current page between two requests, the next page repeats a row; when one is deleted, a row is never shown. use-the-index-luke: "you'll get duplicates in case there were new rows inserted between fetching two pages". The snippet proves both: after inserting a cheaper "Hostel Bed", offset page 2 shows Garden again; after deleting the Studio, the Courtyard is never shown (real, test_insert_between_pages_..., test_delete_between_pages_...). Third: "total must be exact." On a large table the exact count can cost more than the page; many APIs cap it or estimate it.

Definition: Select.limit(n) and Select.offset(m) render LIMIT ? OFFSET ? (SQLite renders OFFSET ? with 0 even when only limit was set: real params (..., 3, 0)). The snippet's paginate_offset runs select(func.count()).select_from(stmt.order_by(None).subquery()) and then stmt.limit(limit).offset(offset). SQLModel's tutorial shows the same offset/limit pair and FastAPI's tutorial bounds limit with Query(le=100).

     GET /rooms?city=Tabriz&city=Shiraz&limit=2&offset=1                      (real, test_list_envelope_and_filters)
1    SELECT count(*) AS count_1 FROM (SELECT room.name, ... FROM room WHERE ... ) AS anon_1     -> 4
2    SELECT room.name, ... WHERE ... ORDER BY room.price_cents, room.id LIMIT ? OFFSET ?       (2, 1)
3    {"items": [Garden, Courtyard], "total": 4, "limit": 2, "offset": 1}      2 statements per request
     page drift (real): page 1 = [Studio, Garden]; INSERT Hostel Bed (3000); page 2 = [Garden, Courtyard]

Real scenario: admin tables with page numbers; search results where users rarely go past page 5; reports exported page by page (where drift is a bug); public APIs where crawlers request offset=1000000.

PropertyOffsetNote
Jump to page Nyesthe reason to choose it
Total and page countyes, one count(*) querycost grows with the filtered row count
Cost of page Ngrows with N (rows produced then discarded)cap offset (le=10_000 in the snippet)
Stable under writesno: duplicates and skipskeyset fixes inserts/deletes; key updates still drift
Needs a unique sortyesotherwise pages overlap even without writes
Laravelpaginate() (with count), simplePaginate() (no count)For PHP/Laravel developers

Fix / how to use it: offset for small, human-navigated lists; a unique sort; bounds on limit and offset; the count over order_by(None); and keyset for feeds, exports and anything deep. The design discussion is in Pagination: Offset vs Keyset.

Page 3 of rooms ORDER BY price_cents, id (20 per page)Offset: LIMIT 20 OFFSET 40Keyset / seek: WHERE (price_cents, id) > (?, ?)rows 1-40: read, sorted,then thrown awayrows 41-60: returnedWork grows with the page number.Insert/delete between pages: duplicates or skips.Measured, 200k rows: 0.03 ms at depth 0, 2.19 msat 199,000; 83.43 ms there without the index.index seek straight tothe last key of page 2next 20 rows (+1 to knowif there is a next page)Work is the same on every page.No total, no jump to page 37; next_cursor only.Measured: 0.03-0.05 ms at every depth (row value).Plain OR form: 4.23 ms at 199,000 (SCAN, no seek).

Keyset pagination: cursor, seek method, next_cursor, row values Must-know ​

In plain words: Remember the sort key of the last row you sent, (9000, 1) for the Garden, and ask for rows after it: WHERE (price_cents, id) > (9000, 1) ORDER BY price_cents, id LIMIT 21. Send 20 back and, if a 21st row came, an opaque next_cursor that encodes (price, id) of the 20th. Every page costs the same, and inserts or deletes between requests cannot shift it. Updates of the sort key itself can: keyset is only as stable as its key is immutable.

Common misunderstanding: "The cursor is a database cursor." It is just the last key, encoded (base64 JSON in the snippet); the server holds no state, which is why it works across instances. Second: "Any correct predicate is fine." The natural price > ? OR (price = ? AND id > ?) is correct but SQLite cannot use it as an index range: SCAN room USING INDEX ix_room_price_id, 4.23 ms at depth 199,000, slower than OFFSET (2.19 ms). The row-value form (price_cents, id) > (?, ?) and the same OR with a redundant leading price_cents >= ? both give SEARCH room USING INDEX ix_room_price_id (price_cents>?) and 0.04 ms at depth 199,000 (real: plans and row-value timing in runs/explain-query-plan.txt, bounded-OR timing in runs/round2.txt). Third: "keyset is stable under any write." It is stable under inserts and deletes, not under updates of a key column: after page 1 ended at (9000, Garden), raising the already-shown Studio from 6000 to 10000 moved it behind the cursor, and page 2 was [Courtyard, Studio, Loft], the Studio a second time (real, test_keyset_repeats_a_row_when_its_sort_key_changes); lowering a price would skip a row instead. For feeds and exports use an immutable key (id, or (created_at, id) where created_at is never updated); for a mutable sort such as price, accept the drift, or snapshot (sort a frozen list of ids, or filter updated_at <= :page1_time). Fourth: "a tampered cursor is the client's problem." Decode it defensively and answer 400, never 500: /rooms/feed?cursor=garbage → 400 {"detail":"Invalid cursor"}, and a well-formed cursor carrying 10**100 also gets 400 because decode_cursor checks both values are real ints inside the signed 64-bit range. Without that check the driver raised OverflowError: Python int too large to convert to SQLite INTEGER, a 500 (real, runs/fix1.txt, test_cursor_feed_walk).

Definition: The seek method "uses the values of the previous page as a delimiter. That means it searches for the values that must come behind the last entry from the previous page." With a multi-column sort, the delimiter is a row value; use-the-index-luke: the row-values syntax "combines multiple values into a logical unit that is applicable to the regular comparison operators". In SQLAlchemy: tuple_(col(Room.price_cents), col(Room.id)) > tuple_(p, i). Fetch limit + 1 rows to know whether a next page exists without a count. Laravel's docs list the same constraints for cursorPaginate(): it "requires that the ordering is based on at least one unique column or a combination of columns that are unique. Columns with null values are not supported."

     GET /rooms/feed?limit=2, then follow next_cursor                           (real, test_cursor_feed_walk)
1    SELECT ... WHERE room.deleted_at IS NULL ORDER BY room.price_cents, room.id LIMIT ? OFFSET ?   (3, 0)
     -> Studio, Garden (+ Courtyard as the extra row)     next_cursor = b64([9000, 1])
2    ... AND room.price_cents >= ? AND (room.price_cents > ? OR room.price_cents = ? AND room.id > ?)  (9000, 9000, 9000, 1, 3, 0)
     -> Courtyard, Loft (+ Harbour Suite)                  next_cursor = b64([12000, 3])
3    ... -> Harbour Suite, no extra row                     next_cursor = null
     3 requests, 3 statements, no COUNT; insert "Hostel Bed" between 1 and 2 -> page 2 still Courtyard, Loft

Real scenario: an infinite-scroll feed of rooms; a mobile app syncing "everything after my last item"; a nightly export of 50 million bookings in batches (the same pattern as Laravel's chunkById()); a public API that must not let offset=10000000 hurt the database.

VariantPredicateSQLite plan (real, explain-query-plan.txt, round2.txt)Portable?
Single unique keyid > ?SEARCH room USING INTEGER PRIMARY KEY (rowid>?)everywhere
OR / AND (naive)price > ? OR price = ? AND id > ?SCAN ... USING INDEXeverywhere, slow
OR / AND + leading boundprice >= ? AND (price > ? OR price = ? AND id > ?)SEARCH ... (price_cents>?)everywhere
Row value(price, id) > (?, ?)SEARCH ... (price_cents>?)PostgreSQL, SQLite 3.15+; MySQL evaluates it but cannot use it for index access (use-the-index-luke)
Descending(price, id) < (?, ?) with DESC, DESCSEARCH room USING INDEX ix_room_price_id (price_cents<?)mixed directions need the OR form
Previous pagereverse the comparison and the order, then reverse the resultnot runcursor stores a direction

Fix / how to use it: keyset for feeds, exports, sync and public APIs; key = sort columns + primary key, all NOT NULL and ideally immutable (id, (created_at, id)); the row-value or bounded OR predicate; an index on exactly that column list; an opaque, validated cursor; limit + 1. Keep offset where users really need page numbers.

Indexes behind ORDER BY and pages: EXPLAIN QUERY PLAN, covering index Important ​

In plain words: A page query is fast when the database can read the rows already in order from an index and stop after LIMIT rows. EXPLAIN QUERY PLAN in SQLite (or EXPLAIN in PostgreSQL/MySQL) tells you whether it does: SCAN room USING INDEX ... reads in index order, SEARCH ... USING INDEX (...) jumps into the index, USE TEMP B-TREE FOR ORDER BY means it sorted all matching rows first.

Common misunderstanding: "I always need a composite (price_cents, id) index for ORDER BY price_cents, id." Not on SQLite when id is the INTEGER PRIMARY KEY: that column is the rowid, every index entry already ends with it, so a price-only index serves the whole sort and even the row-value seek (SEARCH ... USING COVERING INDEX price_only ((price_cents,rowid)>(?,?))). The same holds for a WITHOUT ROWID table, whose indexes carry the primary key. With a non-rowid key, for example a TEXT primary key, the price-only index leaves the ties to a sort: USE TEMP B-TREE FOR LAST TERM OF ORDER BY (real, runs/fix1.txt). On PostgreSQL and MySQL, plan the composite index explicitly: a PostgreSQL B-tree on price_cents does not carry id as a sort key (expected, not run). The snippet declares Index("ix_room_price_id", "price_cents", "id") so the intent is visible and portable. What does hurt is no index on the sort column at all: dropping it turned the depth-199,000 offset page from 2.19 ms into 83.43 ms with USE TEMP B-TREE FOR ORDER BY (real). Second: "a plan is a contract." SQLite warns: "The output format may change between SQLite releases. Applications should not depend on the output format of the EXPLAIN QUERY PLAN command." Assert query counts in tests, read plans by hand.

Definition: An index for ORDER BY has the sort columns as its leading columns in the same order (and directions). A covering index contains every column the query reads, so the table itself is not touched: SQLite prints USING COVERING INDEX. SELECT room.id, room.price_cents ... WHERE room.price_cents > ? was a SEARCH room USING COVERING INDEX ix_room_price_id (price_cents>?) and even count(*) used it, SCAN room USING COVERING INDEX ix_room_price_id, because the index is smaller than the table (real).

     200,000 rooms, SQLite 3.54.0, ANALYZE run                                  (real, runs/explain-query-plan.txt)
1    ORDER BY price_cents, id LIMIT 20 OFFSET 199000      SCAN room USING INDEX ix_room_price_id     2.19 ms
2    same, index dropped                                  SCAN room + USE TEMP B-TREE FOR ORDER BY   83.43 ms
3    (price_cents, id) > (?, ?) ... LIMIT 20              SEARCH room USING INDEX ix_room_price_id (price_cents>?)  0.04 ms
4    ORDER BY city, id (no index on city)                 SCAN room + USE TEMP B-TREE FOR ORDER BY
5    SELECT id, price_cents WHERE price_cents > ?         SEARCH room USING COVERING INDEX ix_room_price_id (price_cents>?)
6    booking overlap for one room                         SEARCH booking USING INDEX ix_booking_room_start (room_id=? AND start_date<?)

Real scenario: a list that was fast in staging (500 rows) and slow in production (5 million); a new sort option that nobody indexed; a count query that reads the whole table; an overlap check for one room that scans all bookings because the index starts with start_date instead of room_id.

Query shapeIndexWhy
ORDER BY price_cents, id LIMIT n(price_cents, id); on SQLite with an INTEGER PRIMARY KEY, (price_cents) suffices (rowid carried, real)read in order, stop after n
WHERE city = ? ORDER BY price_cents, id(city, price_cents, id)equality columns first, then the sort
keyset (price_cents, id) > (?, ?)(price_cents, id)the seek starts inside the index
overlap room_id = ? AND start_date < ? AND end_date > ?(room_id, start_date)equality first, then one range
SELECT id, price_cents WHERE price_cents > ?(price_cents, id) coveringno table access
ORDER BY a computed averagenoneprecompute into a column, index that
PostgreSQL index-only scancovering index + visibility map"index-only scans" in the PostgreSQL docs (expected, not run)

Fix / how to use it: for every list endpoint, run its statements through EXPLAIN QUERY PLAN (the snippet's app/explain_demo.py shows how to compile an ORM statement with its parameters), create the composite index in an Alembic migration (Alembic Migrations, Transactions & Indexes), and keep the worked plans for PostgreSQL in the SQL Queries & Indexes Cheatsheet and the theory in Indexing.

exists and select exists Must-know ​

In plain words: "Is there at least one?" is EXISTS. select(exists().where(Booking.room_id == g)) returns one boolean, and the database stops at the first matching row. Inside a WHERE, exists() (or ~exists()) filters outer rows by whether related rows exist.

Common misunderstanding: "count(...) > 0 is the same." The answer is the same but the work is not: a count must find every matching row, EXISTS stops at the first. Second: "if room.bookings:." That loads the whole collection to test one bit. Third: session.exec(select(exists()...)).one() in SQLModel with a SQLAlchemy select returns a Row like (True,), which is always truthy; the snippet's first version had exactly that bug (real: assert (True,) is True failed). Use session.scalar(...).

Definition: sqlalchemy.exists() builds an Exists construct; "The SQL EXISTS keyword is an operator that is used with scalar subqueries to return a boolean true or false depending on if the SELECT statement would return a row." Wrapped in select() it becomes a one-row, one-column query; in where() it is correlated with the outer query automatically when it references the outer table.

     has_bookings_exists(Garden)  vs  count_bookings(Garden)  vs  len()        (real, test_exists_count_len_...)
1    SELECT EXISTS (SELECT * FROM booking WHERE booking.room_id = ?) AS anon_1                 -> 1 (True)
2    SELECT count(*) AS count_1 FROM booking WHERE booking.room_id = ?                          -> 2
3    SELECT booking.id, booking.room_id, booking.user_id, booking.start_date, ... WHERE ...    -> 2 objects built
     availability inside WHERE:
4    ... AND NOT (EXISTS (SELECT * FROM booking WHERE booking.room_id = room.id AND booking.start_date < ? AND booking.end_date > ?))

Real scenario: "can this user delete the room? only if no future bookings"; "show the review button only if the user stayed there"; "rooms with no bookings at all"; uniqueness pre-checks (racy without a unique constraint).

NeedWriteReturns
Any row?session.scalar(select(exists().where(...)))True/False
Rows whose children exist.where(exists().where(Child.parent_id == Parent.id))filtered parents
Rows without children.where(~exists().where(...))anti-join
Same via a relationship.where(col(Room.bookings).any())EXISTS generated for you
From a subqueryselect(Booking.id).where(...).exists()Exists from a SELECT

Fix / how to use it: session.scalar(select(exists().where(...))) for yes/no; exists() or any() in WHERE for "has/has no related rows"; never len() or count() > 0 for a boolean.

Counting: func.count vs len, count of a filtered query Must-know ​

In plain words: select(func.count()).select_from(Booking).where(...) makes the database count and send one integer. len(session.exec(select(Booking)).all()) sends every row, builds every object, then counts the list.

Common misunderstanding: "count() on a join counts parents." A join multiplies rows: one room with three bookings counts three. Count func.count(col(Room.id).distinct()), or count over a subquery, or count with exists()/any() filters instead of joins. Second: "func.count(Booking.id) and func.count() are the same." count(*) counts rows, count(column) counts non-NULL values: with a LEFT OUTER JOIN, a room without bookings has one row with booking.id NULL, so count(booking.id) is 0 and count(*) would be 1 (real outer-join report shows Attic 0, Studio 0).

Definition: func.count() renders count(*), func.count(expr) renders count(expr), func.count(expr.distinct()) renders count(DISTINCT expr). To count the result of an arbitrary filtered statement, wrap it: select(func.count()).select_from(stmt.order_by(None).subquery()). Removing the ORDER BY makes the subquery cheaper and avoids sorting rows only to count them (real SQL asserted in test_offset_envelope_total_ignores_limit).

     count for the envelope of a filtered query                               (real)
1    stmt = apply_room_filter(select(Room), f).order_by(price, id)
2    select(func.count()).select_from(stmt.order_by(None).subquery())
3    SELECT count(*) AS count_1 FROM (SELECT room.name AS name, ..., room.deleted_at AS deleted_at
        FROM room WHERE room.deleted_at IS NULL AND ... ) AS anon_1         -- no ORDER BY, no LIMIT

Real scenario: "N results" next to a search box; badge counters ("3 unread"); pagination totals; quota checks ("at most 5 active listings per host"); dashboards.

CountSQLAlchemySQL
All rows of a tableselect(func.count()).select_from(Booking)SELECT count(*) FROM booking
Filtered... .where(Booking.room_id == g)... WHERE booking.room_id = ?
Non-null valuesfunc.count(col(Booking.user_id))count(booking.user_id)
Distinct valuesfunc.count(col(Booking.room_id).distinct())count(DISTINCT booking.room_id)
Any statementselect(func.count()).select_from(stmt.order_by(None).subquery())count(*) FROM (...) AS anon_1
Per groupselect(Room.city, func.count(col(Room.id))).group_by(Room.city)GROUP BY room.city
Approximate (PostgreSQL)reltuples from pg_class via text()"only an estimate used by the planner", updated by VACUUM/ANALYZE (expected, not run)

Fix / how to use it: count in SQL; count over a subquery for envelopes; distinct() or EXISTS-based filters when joins would multiply rows; for very large tables, consider no total at all (keyset) or an estimate.

Scalar and correlated subqueries Important ​

In plain words: A scalar subquery is a SELECT that returns one value, used like a column. When it refers to the outer row (WHERE review.room_id = room.id) it is correlated: the database computes it per outer row. It is how you add "average rating" as a column without grouping the whole query.

Common misunderstanding: "A correlated subquery is always slow." With an index on the inner filter column (review.room_id) it is one index lookup per outer row, and for one page of 20 rooms that is cheap; it is a problem when it runs for every row of a big table, for example inside an ORDER BY over the whole table. Second: ".correlate(Room) guarantees correlation." It only names room as a correlation candidate; nothing fails when the enclosing query has no room. Real (runs/fix1.txt): inside select(Room.name, subq) it renders (SELECT avg(review.rating) ... FROM review WHERE review.room_id = room.id), but select(subq) alone renders FROM review, room WHERE review.room_id = room.id, an uncorrelated join that returned 4.0, the average over every review, silently. correlate_except(Review) and no correlate call at all rendered the same FROM review, room there. The guard is a test that asserts the rendered SQL (the snippet's test_correlated_scalar_subquery_column) and always selecting the subquery next to the outer table.

Definition: SQLAlchemy tutorial: "A scalar subquery is a subquery that returns exactly zero or one row and exactly one column. ... A correlated subquery is a scalar subquery that refers to a table in the enclosing SELECT statement." Build it with select(func.avg(Review.rating)).where(Review.room_id == Room.id).correlate(Room).scalar_subquery() and give it a .label("avg_rating"). With no reviews the subquery yields NULL, so Studio and Attic come back as None (real).

     rooms_with_avg_rating                                                     (real, test_correlated_scalar_subquery_column)
1    SELECT room.name,
2           (SELECT avg(review.rating) AS avg_1 FROM review WHERE review.room_id = room.id) AS avg_rating
3    FROM room ORDER BY room.id
     -> Garden 4.5, Harbour Suite 4.33, Loft 2.0, Studio None, Courtyard 4.0, Attic None

Real scenario: "latest booking date" per room on a card; "number of open tickets" per customer in an admin list; sorting by a computed value (sort=rating); a filter "rooms whose average rating is at least 4".

FormShapeWhen
Scalar subquery columnselect(Room.name, avg_subq.label(...))one value per row, few rows
Correlated in WHERE.where(avg_subq >= 4)filter on a computed value
Correlated in ORDER BYorder_by(nulls_last(avg_subq.desc()))small result sets
GROUP BY + joinselect(Room.name, func.avg(...)).join(...).group_by(...)many aggregates at once
Derived table.subquery() joined backreuse one aggregate many times
Precomputed columnroom.avg_rating updated on writebig tables, hot sort keys

Fix / how to use it: correlated scalar subqueries for a value per row on a page; group_by for reports; index the inner filter column; precompute when you sort a large table by it.

Aggregates: func.avg, func.count, group_by, having, label Must-know ​

In plain words: func.<name>(...) calls any SQL function. Put aggregates next to the grouping columns in select(), add .group_by(...), filter groups with .having(...), and name results with .label("rooms") so you can order by them. The result is rows of plain values, not model objects.

Common misunderstanding: "WHERE and HAVING are interchangeable." WHERE filters rows before grouping, HAVING filters groups after: "only live rooms" is WHERE (deleted_at IS NULL), "cities with at least two rooms" is HAVING (count(room.id) >= 2). Second: "an inner join for a per-room report." Rooms with no bookings vanish; use outerjoin and count a column of the outer table (real: inner join returns four rooms, outer join six, with Attic and Studio at 0). Third: "func.avg returns a float." It returns whatever the driver gives: float on SQLite (real), possibly a Decimal-like numeric elsewhere, and None for an empty group. Convert and round at the edge.

Definition: PostgreSQL's aggregate reference lists count, sum, avg, min, max, string_agg, array_agg, bool_and and more; SQLAlchemy's func renders any of them by name (func.avg(Room.price_cents) → avg(room.price_cents)), and .label() adds AS name.

     city_stats(min_rooms=2)                                                   (real, test_group_by_having_with_labels)
1    SELECT room.city, count(room.id) AS rooms, avg(room.price_cents) AS avg_price,
2           min(room.price_cents) AS min_1, max(room.price_cents) AS max_1
3    FROM room WHERE room.deleted_at IS NULL            -- WHERE: rows (the deleted Attic is gone)
4    GROUP BY room.city HAVING count(room.id) >= ?      -- HAVING: groups (Bandar Abbas has 1)
5    ORDER BY rooms DESC, room.city                      -- order by the label
     -> [("Shiraz", 2, 7500.0, 6000, 9000), ("Tabriz", 2, 10500.0, 9000, 12000)]

Real scenario: "average rating" on a room card; revenue per month; "hosts with more than 10 bookings this year"; price ranges per city on a landing page; a dashboard with counts by status.

NeedSQLAlchemyPitfall
Per-group countfunc.count(col(Room.id)).label("rooms") + group_by(Room.city)every non-aggregated selected column must be grouped
Averagefunc.avg(Room.price_cents)None for an empty group
Filter groups.having(func.count(col(Room.id)) >= 2)repeat the expression (portable) or use the label where supported
Order by an aggregate.order_by(rooms.desc()) with rooms the labelled columnrenders ORDER BY rooms DESC
Keep empty parents.outerjoin(Booking, ...) + func.count(col(Booking.id))count(*) would count 1
Several aggregates of a childone group_by query or correlated subqueriesjoining two child tables multiplies rows
Conditional countfunc.count().filter(Booking.guests > 2)renders count(*) FILTER (WHERE booking.guests > ?), ran on SQLite → (5, 1) (real); see Advanced SQL

Fix / how to use it: aggregates in SQL, WHERE before HAVING, labels for readability and ordering, outerjoin for reports that must list every parent, conversion of avg results at the API boundary.

Joins vs relationship loading: join, outerjoin, selectinload for filters, contains_eager Must-know ​

In plain words: A join decides which rows come back; a loader option (selectinload, joinedload) decides how related objects are loaded for the rows that came back. They are independent. Filtering rooms by Alice's bookings with a join does not make room.bookings contain only Alice's bookings.

Common misunderstanding: "select(Room).join(Booking).where(Booking.user_id == alice).options(selectinload(Room.bookings)) gives me Alice's bookings per room." The selectinload runs a second query for all bookings of the matched rooms: the Garden comes back with Alice's and Bob's bookings (real, test_join_filter_does_not_filter_the_loaded_collection). To fill the collection from the filtered join, use contains_eager(Room.bookings): one statement, and garden.bookings holds only Alice's (real). Second: "a join to filter is fine." A one-to-many join returns the parent once per matching child; without .distinct() (or unique() for joined eager loads) the list repeats rooms. any() avoids the duplication entirely.

Definition: Select.join(target, onclause) adds an INNER JOIN, Select.outerjoin(...) a LEFT OUTER JOIN. selectinload(attr) emits SELECT ... WHERE child.parent_id IN (...) after the main query; contains_eager(attr) tells the ORM that the joined columns already in the statement are the collection's contents. Because the identity map may already hold a fully loaded Garden, the snippet adds execution_options(populate_existing=True) so the filtered rows replace the existing collection.

     Rooms Alice booked, two ways                                                (real)
1    join + selectinload   SELECT DISTINCT room.* FROM room JOIN booking ON booking.room_id = room.id WHERE booking.user_id = ?
2                          SELECT booking.* FROM booking WHERE booking.room_id IN (?, ?)    -> Garden.bookings = [Alice, Bob]
3    join + contains_eager SELECT booking.*, room.* FROM room JOIN booking ON ... WHERE booking.user_id = ?
                           -> Garden.bookings = [Alice]                                     1 statement

Real scenario: "my bookings grouped by room" (contains_eager); "rooms that have at least one 5-star review, with all their reviews" (any + selectinload); a report joining rooms and bookings to aggregate (join + group_by); an admin list that must show rooms even without bookings (outerjoin).

GoalWriteStatements
Filter parents by a child condition.where(col(Room.bookings).any(Booking.user_id == a))1, no duplicates
Filter + load all childrenany(...) + selectinload(Room.bookings)2
Filter + load only matching children.join(Booking).where(...) + contains_eager(Room.bookings)1
Aggregate children.outerjoin(Booking) + group_by1
Load children, no filterselectinload(Room.bookings)2 (1 + ceil(N/500))
Many-to-one data in the rowjoinedload(Booking.room)1

Fix / how to use it: filter with any()/has() or explicit joins, load with options, and use contains_eager only when the collection is meant to be the filtered subset. Loader strategies themselves are in SQLAlchemy 2 & SQLModel.

In plain words: col(Room.amenities).any(Amenity.name == "wifi") means "rooms with at least one amenity named wifi" and renders a correlated EXISTS. ~...any() means "rooms with none". col(Booking.room).has(Room.city == "Tabriz") is the many-to-one version. col(Room.amenities).contains(kitchen) tests membership of one object.

Common misunderstanding: "amenity=wifi&amenity=kitchen is Amenity.name.in_([...])." With a join and in_ you get rooms with wifi or kitchen. "Has every amenity" is one any() per value, ANDed: the filter returns Loft and Harbour Suite, not Garden (wifi only) (real, two EXISTS in the SQL). Second: "has() works on collections." any() is for one-to-many and many-to-many, has() for many-to-one and one-to-one; col(Room.bookings).has(...) raises InvalidRequestError: 'has()' not implemented for collections. Use any(). (real, runs/claims.txt).

Definition: SQLAlchemy query guide: "For a one-to-many relationship such as User.addresses, an EXISTS against the address table that correlates back to the user_account table can be produced using PropComparator.any()", and "The PropComparator.has() method works in mostly the same way as PropComparator.any(), except that it's used for many-to-one relationships". For a many-to-many, the EXISTS joins the link table.

     rooms_with_amenity("balcony")                                                (real)
1    SELECT room.name FROM room WHERE EXISTS (SELECT 1 FROM amenity, roomamenitylink
2      WHERE room.id = roomamenitylink.room_id AND amenity.id = roomamenitylink.amenity_id AND amenity.name = ?)
3    ORDER BY room.name                                     -> Courtyard, Harbour Suite
     bookings_in_city("Tabriz"):  WHERE EXISTS (SELECT 1 FROM room WHERE room.id = booking.room_id AND room.city = ?)  -> 1, 2, 4
     rooms_without_bookings:      WHERE NOT (EXISTS (SELECT 1 FROM booking WHERE room.id = booking.room_id)) -> Attic, Studio

Real scenario: "hotels with parking and a pool"; "orders that contain a discounted item"; "users who never logged in" (~any()); "bookings in rooms of one host" (has()); tagging systems ("posts tagged python and fastapi").

RelationshipOperatorSQLLaravel
one-to-manycol(Room.bookings).any(cond)EXISTS (SELECT 1 FROM booking WHERE room.id = booking.room_id AND cond)whereHas('bookings', fn)
none~col(Room.bookings).any()NOT (EXISTS (...))doesntHave('bookings') / whereDoesntHave
many-to-manycol(Room.amenities).any(Amenity.name == x)EXISTS over link + targetwhereHas('amenities', ...)
all of severaland_(any(x1), any(x2))two EXISTStwo whereHas
many-to-onecol(Booking.room).has(Room.city == c)EXISTS (SELECT 1 FROM room WHERE room.id = booking.room_id AND ...)whereHas('room', ...) / whereBelongsTo
membershipcol(Room.amenities).contains(obj)EXISTS/join on the object's keywhereRelation

Fix / how to use it: any()/has() for relationship filters in filter models; one any() per required value; an index on the child's foreign key (review.room_id has one; the link table's primary key covers (room_id, amenity_id), real plan in Mechanics).

Date ranges: date range overlap, half-open intervals, between Must-know ​

In plain words: Store a booking as [start_date, end_date): the guest arrives on start_date and leaves on end_date. Two ranges overlap when a.start < b.end AND a.end > b.start. "Free between X and Y" is NOT EXISTS an overlapping booking. between(a, b) is a different tool: it is inclusive on both ends.

Common misunderstanding: "between(check_in, check_out) finds overlapping bookings." It only finds bookings whose start falls inside the range, and it is inclusive on both ends, so a booking that starts on the checkout day is counted although the room is free that night. Real: bookings_starting_between(Dec 1, Dec 3) returns bookings 1, 3 and 5, including the one that starts exactly on Dec 3. Second: "<= is safer than <." With half-open ranges <= blocks back-to-back stays: [Dec 4, Dec 10) is free between Garden's [Dec 1, Dec 4) and [Dec 10, Dec 12) (real).

Definition: overlaps(start, end) = (col(Booking.start_date) < end) & (col(Booking.end_date) > start); room_is_free is not session.scalar(select(exists().where(Booking.room_id == r, overlaps(s, e)))). The rule covers partial overlap, containment in both directions and identical ranges with one comparison pair. PostgreSQL has native range types (daterange, the && overlap operator) and exclusion constraints that make the database reject overlaps (expected, not run).

     Garden bookings: [Dec 1, Dec 4) and [Dec 10, Dec 12)                     (real, test_overlap_boundaries)
1    [Dec 3, Dec 5)     1 < 5 and 4 > 3                        -> overlap  -> free=False
2    [Dec 4, Dec 10)    4 < 4? no   ;  10 < 10? no              -> free=True  (back to back)
3    [Nov 28, Dec 15)   contains both                           -> overlap
4    [Dec 2, Dec 3)     inside the first                         -> overlap
5    [Nov 29, Dec 1)    ends the day the first starts            -> free=True
     between(Dec 1, Dec 3) on start_date -> bookings 1 (Dec 1), 3 (Dec 2), 5 (Dec 3)   inclusive both ends

Real scenario: hotel and rental availability; meeting rooms with time slots; doctor appointments; "bookings created this month" reports (>= first AND < first_of_next); price seasons that must not overlap.

NeedSQLSQLAlchemy
Overlapa.start < :end AND a.end > :startoverlaps(start, end)
Free roomNOT EXISTS (overlapping booking of this room)~exists().where(Booking.room_id == Room.id, overlaps(...))
Inside a monthcreated_at >= :first AND created_at < :next_firsttwo comparisons, half-open
Inclusive rangex BETWEEN :a AND :bcol(x).between(a, b)
Validate inputend > startmodel_validator / route check (422)
Index(room_id, start_date)Index("ix_booking_room_start", ...), real SEARCH ... (room_id=? AND start_date<?)
Prevent races (PostgreSQL)EXCLUDE USING gist (room_id WITH =, daterange(start_date, end_date) WITH &&) with btree_gistexpected, not run

Fix / how to use it: half-open ranges everywhere, one overlaps() helper for the check and the search, between only when you mean inclusive, and a database constraint or lock against concurrent double bookings (covered in SQLAlchemy 2 & SQLModel).

Timezone-aware datetimes: DateTime(timezone=True), AwareDatetime, UTC Must-know ​

In plain words: Store instants (when something happened) as timezone-aware values in UTC, accept only aware values from clients, and convert to local time only for display. DateTime(timezone=True) asks the database for a time-zone-aware column; Pydantic's AwareDatetime refuses input without an offset.

Common misunderstanding: "DateTime(timezone=True) makes it safe everywhere." On PostgreSQL it maps to timestamptz: "All timezone-aware dates and times are stored internally in UTC." On SQLite there is no such type ("SQLite does not have a storage class set aside for storing dates and/or times"); SQLAlchemy stores an ISO string and drops the offset without converting. Real: 13:30+03:30 written through a plain DateTime(timezone=True) column was stored as 2026-11-22 13:30:00.000000 and read back as a naive 13:30, three and a half hours wrong (test_plain_datetime_timezone_true_drops_the_offset_on_sqlite). The snippet's UTCDateTime TypeDecorator converts to UTC before binding (stored 2026-11-22 10:00:00.000000) and attaches UTC when reading. Second: "naive datetimes are UTC." A naive value has no zone at all; UTCDateTime raises naive datetime: pass an aware datetime (UTC) instead of guessing (real, wrapped by SQLAlchemy in StatementError).

Definition: Pydantic: "AwareDatetime: Requires the input to have a timezone." As a query parameter, since: AwareDatetime turns ?since=2026-11-22T10:00:00 into 422 {"type":"timezone_aware","msg":"Input should have timezone info"} and accepts 2026-11-22T13:30:00+03:30 (real, curl-run.txt). Responses serialise UTC as "2026-11-22T10:00:00Z" (real). Python's datetime.now(timezone.utc) is the aware "now".

     the same instant, three writings                                         (real, test_dates)
1    client sends     2026-11-22T13:30:00+03:30         (Tehran)
2    AwareDatetime    ok; UTCDateTime binds 2026-11-22 10:00:00 UTC
3    SQLite stores    '2026-11-22 10:00:00.000000'
4    read back        datetime(2026, 11, 22, 10, 0, tzinfo=timezone.utc) -> JSON "2026-11-22T10:00:00Z"
5    since=13:30+03:30 and since=10:00+00:00 return the same bookings [3, 4, 5]
     plain DateTime(timezone=True) on SQLite: stores '2026-11-22 13:30:00.000000', reads naive 13:30

Real scenario: bookings created from apps in several countries; "bookings in the last 24 hours" across a DST change; audit logs compared across services; a nightly job in UTC that must not miss records written in local time.

LayerDoAvoid
API inputAwareDatetime (or Field with AwareDatetime)naive datetime
Pythondatetime.now(timezone.utc)datetime.now(), datetime.utcnow() (naive)
PostgreSQLtimestamptz (DateTime(timezone=True))timestamp for instants
SQLiteTypeDecorator that stores UTCDateTime(timezone=True) alone (offset dropped, real)
MySQLDATETIME storing UTC by convention, or TIMESTAMPrelying on the session time zone
Dates (check-in day)date, no time zonedatetime at midnight
OutputISO 8601 with offset/Zlocal time without offset

Fix / how to use it: aware in, UTC in the database, aware out; a TypeDecorator on SQLite; plain date for calendar days; local conversion in the client. The Pydantic side of datetime parsing is in Typing & Pydantic v2.

Bulk update and bulk delete: update(), delete(), synchronize_session Important ​

In plain words: session.exec(update(Room).where(Room.city == "Tabriz").values(price_cents=Room.price_cents * 110 // 100)) changes every matching row with one statement, without loading objects. delete(Room).where(...) deletes with one statement. synchronize_session decides what happens to matching objects already loaded in the session.

Common misunderstanding: "The objects in my session see the new values." With synchronize_session=False they do not: the Garden loaded before the UPDATE still says 9000 until the session expires it (real, parametrised test: auto, evaluate and fetch show 9900, False shows 9000; after commit() all show 9900). Second: "bulk delete runs my ORM cascades." It does not; the docs: "The operations do not offer in-Python cascading of relationships - it is assumed that ON UPDATE CASCADE and/or ON DELETE CASCADE is configured for any foreign key references which require it". Third: "/ is integer division." In SQLAlchemy 2.0, / on integers is true division and rendered ((room.price_cents * ?) / (? + 0.0)) on SQLite (real, runs/claims.txt); // renders an integer division ((room.price_cents * ?) / ?).

Definition: The docs list 'auto' ("this is the default. The 'fetch' strategy will be used on backends that support RETURNING ... If RETURNING is not supported, the 'evaluate' strategy will be used instead"), 'fetch' ("Retrieves the primary key identity of affected rows by either performing a SELECT before the UPDATE or DELETE, or by using RETURNING"), 'evaluate' ("evaluate the WHERE criteria given in the UPDATE or DELETE statement in Python, to locate matching objects within the Session") and False ("don't synchronize the session"). The installed 2.0.58 source documents 'auto' differently: "'auto' checks if we can use 'evaluate' first, then falls back to 'fetch'", and the run agrees: on SQLite, which supports RETURNING, 'auto' sent the UPDATE without RETURNING while 'fetch' added RETURNING id (real, runs/sql-echo.txt step 9).

     raise_prices("Tabriz", 10) with Garden already loaded                     (real, test_bulk_update_and_synchronize_session)
1    sync='auto'      UPDATE room SET price_cents=((room.price_cents * ?) / ?) WHERE room.city = ?   (110, 100, 'Tabriz')
                      garden.price_cents == 9900       (evaluated in Python, no extra SQL)
2    sync='fetch'     ... WHERE room.city = ? RETURNING id      garden.price_cents == 9900
3    sync=False       same UPDATE, no sync                       garden.price_cents == 9000   (stale)
4    session.commit() expires everything                         garden.price_cents == 9900   (fresh SELECT)
     rowcount == 3 (Garden, Loft and the soft-deleted Attic: bulk statements ignore your soft-delete filter too)

Real scenario: a price increase for a city; marking all past bookings as completed; deleting expired sessions or tokens; archiving old rows in batches; GDPR erasure of a user's data.

ValueSQL round tripsLoaded objectsUse when
'auto' (default)0 extra on 2.0.58 when evaluable (real)updated / moved to deletednormal case
'evaluate'0 extraupdated in Python; may raise for complex WHEREsimple criteria, few loaded objects
'fetch'RETURNING or a SELECT firstrefreshed / expungedcomplex criteria, many expired objects
False0 extraunchanged (stale)the session holds no affected objects
Core on session.connection()0 extranever synchronisedmaximum control
session.execute(update(Room), [dicts])ORM bulk UPDATE by primary keymany rows, different values

Fix / how to use it: keep the default 'auto', use False only in jobs whose session is empty, // for integer arithmetic, database ON DELETE actions for anything a bulk delete must cascade to, batches for very large updates (SQLAlchemy 2.0's update() and delete() have no .limit(): select a bounded, ordered slice of ids with select(Room.id).where(Room.id > last).order_by(Room.id).limit(n), then update(Room).where(col(Room.id).in_(ids)), commit, continue after the last id; raise_prices_in_batches does this and test_batched_update_selects_bounded_ids_then_updates_them asserts two UPDATE ... IN (...) statements for batches [2, 1], real), and explicit soft-delete conditions in bulk statements.

Deleting rooms: who deletes the children? (measured on SQLite, foreign keys ON)session.delete(room)ORM unit of work runsSELECT booking WHERE ? = room_idSELECT amenity via roomamenitylinkDELETE FROM roomamenitylink ...DELETE FROM booking WHERE id = ? (executemany, 2 rows)DELETE FROM room WHERE id = ?reviews: passive_deletes='all', never SELECTed; ON DELETE CASCADEdelete(Room).where(...)bulk DELETE, one statement:DELETE FROM room WHERE city = ?no ORM cascade runs at allbookings + reviews removed by ON DELETE CASCADE in the databaselink rows: ON DELETE CASCADEobjects already in the session stay until commit / expire_allsame, foreign keys OFFSQLite default per connection:PRAGMA foreign_keys is OFFDELETE FROM room WHERE city = ?3 rooms gone; 3 bookings and 3 reviews left pointing at rooms that do not existfix: PRAGMA foreign_keys=ON on every connect (event listener)Schema in the snippet: booking.room_id ON DELETE CASCADE + Room.bookings cascade_delete=True ("all, delete-orphan");review.room_id ON DELETE CASCADE + passive_deletes="all"; booking.user_id ON DELETE SET NULL + passive_deletes=True.Soft delete (deleted_at) runs none of these: an UPDATE, history kept, every query must filter it.

Cascade rules: cascade all delete-orphan, ondelete CASCADE, SET NULL, passive_deletes Must-know ​

In plain words: When a room is deleted, something must happen to its bookings and reviews. Either the ORM deletes them (cascade="all, delete-orphan", which SQLModel spells cascade_delete=True), or the database does (ondelete="CASCADE" on the foreign key), or both. passive_deletes tells the ORM to trust the database instead of loading children to delete them. SET NULL keeps the child and forgets the parent.

Common misunderstanding: "ORM cascade is enough." It only runs for session.delete(obj); a bulk delete(), a SQL console or another service deleting the row skips it. The database rule is the one that always holds, if the database enforces foreign keys (SQLite only with PRAGMA foreign_keys=ON per connection). Real: the same bulk delete removed 3 bookings and 3 reviews with foreign keys ON and left them all orphaned with foreign keys OFF. Second: "delete-orphan means delete when the parent is deleted." It also deletes a child that is merely removed from the collection (room.bookings.remove(b)); the SQLAlchemy docs note that "delete-orphan cascade is normally configured only on the "one" side of a one-to-many relationship".

Definition: SQLAlchemy: passive_deletes "indicates the degree to which the ORM should try to run DELETE/UPDATE operations on related rows itself, vs. how much it should rely upon expecting the database-side FOREIGN KEY constraint cascade to handle the task; ... it accepts options False (the default), True and "all"." PostgreSQL: "The default ON DELETE action is ON DELETE NO ACTION", "RESTRICT is a stricter setting than NO ACTION", and "The actions SET NULL or SET DEFAULT can be appropriate if a foreign-key relationship represents optional information." SQLModel's cascade tutorial covers cascade_delete on Relationship(), ondelete on Field() and passive_deletes="all".

     session.delete(garden); commit()                                           (real, runs/sql-echo.txt step 10)
1    SELECT booking.* FROM booking WHERE ? = booking.room_id         cascade_delete=True: load the children
2    SELECT amenity.* FROM amenity, roomamenitylink WHERE ? = roomamenitylink.room_id ...   many-to-many link rows
3    DELETE FROM roomamenitylink WHERE roomamenitylink.room_id = ? AND roomamenitylink.amenity_id = ?
4    DELETE FROM booking WHERE booking.id = ?                         executemany [(1,), (2,)]
5    DELETE FROM room WHERE room.id = ?                               reviews: never selected; ON DELETE CASCADE removes 2
     bulk: DELETE FROM room WHERE room.city = ?   (one statement; database cascades only)

Real scenario: deleting a room deletes its bookings (composition); deleting a user keeps their bookings for accounting with user_id = NULL; deleting a product must be refused while orders reference it (RESTRICT); deleting a tenant removes everything (cascade, usually as a background job).

Rule in the snippetModelDatabaseWhat session.delete(parent) does (real)
Room → bookingscascade_delete=True ("all, delete-orphan")ON DELETE CASCADEloads bookings, deletes them, then the room
Room → reviewspassive_deletes="all"ON DELETE CASCADEnever loads reviews; database deletes them
Room → amenity linkmany-to-many link_modelON DELETE CASCADEdeletes link rows itself
User → bookingspassive_deletes=TrueON DELETE SET NULLunloaded bookings: database sets NULL (real: booking 2 user_id None)
Product → order lines (typical, not in the snippet)no cascadeON DELETE RESTRICTIntegrityError, map to 409 (expected, not run here; the ORM chapter's RESTRICT probe covers it)
Any parent, bulk delete()ignoredappliesdatabase actions only

Fix / how to use it: decide per foreign key (composition: CASCADE; optional reference: SET NULL; independent things: RESTRICT/NO ACTION), put the rule in the database (ondelete=..., created by an Alembic migration), mirror it in the ORM (cascade_delete for small collections you want events for, passive_deletes for large ones), and turn on SQLite foreign keys per connection. The ORM side in depth is in SQLAlchemy 2 & SQLModel.

Soft delete: deleted_at, filtered everywhere with with_loader_criteria Important ​

In plain words: Instead of DELETE, set deleted_at = now(). The row and its history stay; every query must then add deleted_at IS NULL. A do_orm_execute event with with_loader_criteria adds that condition to every ORM SELECT of a session class, so nobody can forget it.

Common misunderstanding: "soft delete is free safety." Every query, unique constraint and index now has to consider deleted rows: the unique name still blocks a new room named "Attic"; counts and joins include deleted rows unless filtered; bulk update()/delete() are not ORM SELECTs and ignore the global filter (real: raise_prices("Tabriz") updated the soft-deleted Attic too, rowcount 3). Second: "soft delete replaces foreign-key cascades." It does nothing to children; bookings of a soft-deleted room remain and must be handled by the query (real: Loft soft-deleted, booking 4 still there).

Definition: SQLAlchemy's session-events page describes adding criteria to all queries "by making use of the with_loader_criteria() query option". The snippet's SoftDeleteSession listens to do_orm_execute, skips column and relationship loads, honours execution_options(include_deleted=True) and appends with_loader_criteria(Room, lambda cls: cls.deleted_at.is_(None), include_aliases=True). The API's DELETE /rooms/{id} sets an aware deleted_at and returns 204; the second call returns 404 (real).

     SoftDeleteSession                                                          (real, test_soft_delete_session_hides_deleted_rooms)
1    select(Room.name)                                   -> 5 names, "Attic" hidden
2    select(Room).execution_options(include_deleted=True) -> 6 rooms
3    soft_delete_room(Loft, now); commit()
4    select(Room.name)                                   -> Courtyard, Garden, Harbour Suite, Studio
     DELETE /rooms/3 -> 204; again -> 404; GET /rooms no longer lists Loft; booking 4 kept

Real scenario: "undo delete" in an admin UI; legal retention of bookings after a room is retired; tenants that are deactivated, not erased; audit requirements. The opposite requirement, GDPR erasure, needs a real delete.

ApproachProsCons
Hard delete + ON DELETEsimple, constraints stay truehistory gone
deleted_at + explicit filtersvisible in codeeasy to forget one query
deleted_at + with_loader_criteria eventapplied to every ORM SELECTnot to bulk DML or text(); surprising for newcomers
Archive table (move row)live table stays small and cleantwo schemas to migrate
PostgreSQL partial unique index WHERE deleted_at IS NULLnames reusable after deleteper-database DDL (expected, not run)
Laravel SoftDeletes traitglobal scope built insame caveats for raw queries

Fix / how to use it: choose soft delete only when the product needs history or undo; apply the filter centrally; add partial unique indexes where names must be reusable; remember bulk DML and raw SQL; keep a hard-delete path for erasure.

GET /rooms/with-bookings?limit=N: statements per request (measured)Before: lazy loading in the loopSELECT room.* FROM room (all rows, no LIMIT)SELECT booking.* WHERE ? = booking.room_id (1)SELECT booking.* WHERE ? = booking.room_id (2)...SELECT booking.* WHERE ? = booking.room_id (N)1 + N statements: 7 for the 6 seeded rooms.total = len(all rows); paging done in Python.The test passes on 6 rows and the endpointtimes out on 60,000.After: selectinload(Room.bookings)SELECT room.* WHERE deleted_at IS NULLORDER BY price_cents, id LIMIT ? OFFSET ?SELECT booking.* WHERE booking.room_idIN (?, ?, ...) one IN list for the page2 statements for limit=2 and for limit=100.The test asserts the count, so a new lazyattribute in the response model fails CI.Counted with an event listener:event.listen(engine, "before_cursor_execute", fn)fires once per statement sent to the driver.

N+1 in list endpoints and measured query counts: event listener, before_cursor_execute Must-know ​

In plain words: A list endpoint that returns rooms with their bookings must send a constant number of statements, whatever the page size. Count them in a test with an event listener on before_cursor_execute, which fires once per statement the driver runs, and assert the number.

Common misunderstanding: "N+1 is visible in code review." In the Before app the loop [b.id for b in room.bookings] looks innocent; response_model serialisation can trigger the same lazy loads with no loop in your code at all. Only a count catches it. Real: Before sends 1 + 6 = 7 statements for six rooms; After sends 2 statements for limit=2 and for limit=100 (test_list_endpoint_query_count_is_constant). Second: "the Before endpoint is fine with limit=2." It sent 1 + 2 statements, but the first one had no LIMIT and loaded all 26 rows to compute total and slice in Python (real, test_before_grows_with_the_table).

Definition: SQLAlchemy core events: before_cursor_execute will "Intercept low-level cursor execute() events before execution, receiving the string SQL statement and DBAPI-specific parameter list to be invoked against a cursor." The listener signature is (conn, cursor, statement, parameters, context, executemany). The snippet's count_queries(engine) context manager registers it with event.listen, ignores PRAGMA statements, records statement and parameters, and removes itself with event.remove.

     test_list_endpoint_query_count_is_constant                                (real)
1    with count_queries(engine) as small: GET /rooms/with-bookings?limit=2      -> small.count == 2
2    with count_queries(engine) as big:   GET /rooms/with-bookings?limit=100    -> big.count == 2
3    big.statements[1] contains " IN ("                                          -> selectinload, not lazy
     before app, GET /rooms?limit=100 -> 7 statements (1 + 6); GET /rooms?limit=2 after +20 rooms -> 3, first without LIMIT

Real scenario: a response model that gains a nested field (bookings, owner) in a later sprint; a serializer that touches room.amenities; a dashboard that slowed down by 100× after a data import; CI that must fail before production does.

ToolWhereWhat it shows
count_queries (before_cursor_execute)testsexact statements and parameters per request
echo=Truelocal runsevery statement in the log
raiseload("*")developmentraises on any lazy load
lazy="raise" on a relationshipmodelforbids lazy loading of that attribute
after_cursor_execute + timerproductionslow-query logging with duration
OpenTelemetry SQLAlchemyInstrumentor (opentelemetry-instrumentation-sqlalchemy)productionspans per statement (docs only, not run)
Laravel Model::preventLazyLoading()Laravelthe same guard

Fix / how to use it: one query-count test per list endpoint with two page sizes, selectinload for collections in list queries, raiseload in development, and the general ORM pitfalls in ORM Pitfalls.

SQL injection safety: bound parameters, text() and identifiers Must-know ​

In plain words: Values must travel next to the SQL as bound parameters, never inside the SQL string. Every SQLAlchemy expression does this automatically; text() does it when you use :name placeholders and pass a dict. The danger is an f-string.

Common misunderstanding: "The ORM protects me everywhere." It does not protect text(f"... '{q}' ..."), order_by(text(sort)) or literal_column(user_input). Real: search_names_fstring(session, "' OR 1=1 --") returned all 6 rooms including the soft-deleted one; search_names_text with the same input returned [] (test_text_with_bound_parameter_vs_fstring_injection), and the Before endpoint leaked the whole table the same way. Second: "bound parameters work for column names." Placeholders carry values only; identifiers (sort columns, table names) must come from an allow-list, which is what the Literal sort key does.

Definition: OWASP's prevention cheat sheet makes parameterized queries the primary defence: "use parameterized queries for dynamic data values". SQLAlchemy's text() accepts named bind parameters (text("... WHERE name LIKE :pattern") with {"pattern": ...}), and the DBAPI (PEP 249) sends them separately; with the sqlite3 driver they appear as ? (real echo line SELECT name FROM room WHERE name LIKE ? ORDER BY name with ('%our%',)).

     q = "' OR 1=1 --"                                                           (real)
1    f-string   SELECT name FROM room WHERE name LIKE '%' OR 1=1 --%' ORDER BY name   -> 6 rows (comment ate the rest)
2    text()     SELECT name FROM room WHERE name LIKE ? ORDER BY name   params ("%' OR 1=1 --%",)  -> []
3    ORM        WHERE ... lower(room.name) LIKE '%' || lower(?) || '%' ESCAPE '/'   -> [], value never in the SQL text

Real scenario: a search box; a "sort by" dropdown; a reporting endpoint with a raw SQL query; a legacy endpoint that builds IN (...) lists by string joining.

Input kindSafe wayUnsafe way
Valuewhere(Room.name == q), text(":q") + paramsf-string, % formatting, +
List of valuescol(x).in_(values); bindparam("ids", expanding=True) in text()",".join(values)
LIKE patternicontains(q, autoescape=True)like(f"%{q}%") (wildcards)
Sort columnLiteral + mapping to columnsorder_by(text(sort))
Table / schema nameallow-listinterpolation
Raw SQLtext() with :nameexec_driver_sql(f"...")

Fix / how to use it: expressions or text() with named parameters, allow-lists for identifiers, a filter model that only accepts known keys, and a test that sends ' OR 1=1 --.

Mechanics ​

How GET /rooms becomes two statements Important ​

     GET /rooms?q=a&city=Tabriz&city=Shiraz&min_capacity=2&amenity=wifi&available_from=2026-12-04&available_to=2026-12-06
1    Starlette parses the query string; repeated keys become lists
2    FastAPI builds RoomFilter from Annotated[RoomFilter, Query()]; extra="forbid"; model_validator checks the date pair
3    get_session (yield dependency) opens one Session on the app's engine
4    apply_room_filter(select(Room), f): one condition per set field, and_(*conditions)
5    .order_by(*room_order("price"))  ->  ORDER BY room.price_cents, room.id
6    paginate_offset: SELECT count(*) FROM (filtered statement without ORDER BY)  ->  total
7    paginate_offset: the statement + LIMIT ? OFFSET ?                              ->  items
8    Page[RoomPublic](items=..., total=..., limit=..., offset=...) validated and serialised
9    session closed after the response; nothing was written, so nothing to commit

The SQL the snippets emit (echo=True) Must-know ​

python -m app.echo_demo seeds the test data, sets engine.echo = True and runs each recipe. The statements below are from runs/sql-echo.txt with these edits: timestamps and [generated in ...] markers removed, parameters shown as comments, semicolons added, the long column lists of steps 2 and 10 shortened to room.*/booking.* where marked.

sql
-- 2. offset page: COUNT over the filtered query, then the page
SELECT count(*) AS count_1
FROM (SELECT room.name AS name, room.city AS city, room.capacity AS capacity, room.price_cents AS price_cents, room.id AS id, room.deleted_at AS deleted_at
FROM room
WHERE room.deleted_at IS NULL
  AND ((lower(room.name) LIKE '%' || lower(?) || '%' ESCAPE '/') OR (lower(room.city) LIKE '%' || lower(?) || '%' ESCAPE '/'))
  AND room.city IN (?, ?) AND room.capacity >= ?
  AND (EXISTS (SELECT 1 FROM amenity, roomamenitylink
               WHERE room.id = roomamenitylink.room_id AND amenity.id = roomamenitylink.amenity_id AND amenity.name = ?))
  AND NOT (EXISTS (SELECT * FROM booking
                   WHERE booking.room_id = room.id AND booking.start_date < ? AND booking.end_date > ?))) AS anon_1;
-- ('a', 'a', 'Tabriz', 'Shiraz', 2, 'wifi', '2026-12-06', '2026-12-04')
SELECT room.* FROM room WHERE /* same conditions */ ... ORDER BY room.price_cents, room.id LIMIT ? OFFSET ?;
-- (..., 20, 0)

-- 3. keyset page after (9000, Garden)
SELECT room.name, room.city, room.capacity, room.price_cents, room.id, room.deleted_at
FROM room
WHERE room.deleted_at IS NULL AND room.price_cents >= ? AND (room.price_cents > ? OR room.price_cents = ? AND room.id > ?)
ORDER BY room.price_cents, room.id LIMIT ? OFFSET ?;
-- (9000, 9000, 9000, 1, 3, 0)

-- 4. sort=rating: correlated scalar subquery, DESC NULLS LAST
SELECT room.name FROM room WHERE room.deleted_at IS NULL
ORDER BY (SELECT avg(review.rating) AS avg_1 FROM review WHERE review.room_id = room.id) DESC NULLS LAST, room.id;

-- 5. exists vs count vs len
SELECT EXISTS (SELECT * FROM booking WHERE booking.room_id = ?) AS anon_1;      -- (1,)
SELECT count(*) AS count_1 FROM booking WHERE booking.room_id = ?;              -- (1,)
SELECT booking.id, booking.room_id, booking.user_id, booking.start_date, booking.end_date, booking.guests, booking.created_at
FROM booking WHERE booking.room_id = ?;                                         -- (1,)

-- 6. GROUP BY / HAVING with labels
SELECT room.city, count(room.id) AS rooms, avg(room.price_cents) AS avg_price, min(room.price_cents) AS min_1, max(room.price_cents) AS max_1
FROM room WHERE room.deleted_at IS NULL GROUP BY room.city
HAVING count(room.id) >= ? ORDER BY rooms DESC, room.city;                      -- (2,)

-- 7. LEFT OUTER JOIN + count
SELECT room.name, count(booking.id) AS bookings
FROM room LEFT OUTER JOIN booking ON booking.room_id = room.id GROUP BY room.id, room.name ORDER BY bookings DESC, room.name;

-- 8. any() / has()
SELECT room.name FROM room WHERE EXISTS (SELECT 1 FROM amenity, roomamenitylink
  WHERE room.id = roomamenitylink.room_id AND amenity.id = roomamenitylink.amenity_id AND amenity.name = ?) ORDER BY room.name;  -- ('balcony',)
SELECT booking.id FROM booking WHERE EXISTS (SELECT 1 FROM room WHERE room.id = booking.room_id AND room.city = ?) ORDER BY booking.id;  -- ('Tabriz',)

-- 9. bulk UPDATE: synchronize_session='auto' (evaluated, no RETURNING) and 'fetch'
UPDATE room SET price_cents=((room.price_cents * ?) / ?) WHERE room.city = ?;              -- (110, 100, 'Tabriz')
UPDATE room SET price_cents=((room.price_cents * ?) / ?) WHERE room.city = ? RETURNING id; -- (105, 100, 'Shiraz')
ROLLBACK;

-- 10. session.delete(room): ORM cascade for bookings and link rows, ON DELETE CASCADE for reviews
SELECT room.* FROM room WHERE room.id = ?;                                       -- (1,)
SELECT booking.* FROM booking WHERE ? = booking.room_id;                         -- (1,)
SELECT amenity.id AS amenity_id, amenity.name AS amenity_name FROM amenity, roomamenitylink
WHERE ? = roomamenitylink.room_id AND amenity.id = roomamenitylink.amenity_id;   -- (1,)
DELETE FROM roomamenitylink WHERE roomamenitylink.room_id = ? AND roomamenitylink.amenity_id = ?;  -- (1, 1)
DELETE FROM booking WHERE booking.id = ?;                                        -- [(1,), (2,)]
DELETE FROM room WHERE room.id = ?;                                              -- (1,)
COMMIT;

-- 11. bulk DELETE: only the database cascades
DELETE FROM room WHERE room.city = ?;                                            -- ('Shiraz',)
COMMIT;

-- 12. text() with a bound parameter
SELECT name FROM room WHERE name LIKE ? ORDER BY name;                           -- ('%our%',)

EXPLAIN QUERY PLAN for the page queries Must-know ​

python -m app.explain_demo inserts 200,000 rooms and 2,000 bookings into an in-memory SQLite 3.54.0 database, runs ANALYZE, compiles each ORM statement with its parameters and prefixes EXPLAIN QUERY PLAN. Output from runs/explain-query-plan.txt (columns: id, parent, detail; column lists shortened to room.*):

sql
-- offset page, index on (price_cents, id)
EXPLAIN QUERY PLAN SELECT room.* FROM room ORDER BY room.price_cents, room.id LIMIT ? OFFSET ?;
--   8   0  SCAN room USING INDEX ix_room_price_id

-- keyset page, OR/AND seek predicate (naive)
EXPLAIN QUERY PLAN SELECT room.* FROM room
WHERE room.price_cents > ? OR room.price_cents = ? AND room.id > ? ORDER BY room.price_cents, room.id LIMIT ? OFFSET ?;
--   8   0  SCAN room USING INDEX ix_room_price_id

-- keyset page, OR/AND plus a leading >= bound
EXPLAIN QUERY PLAN SELECT room.* FROM room
WHERE room.price_cents >= ? AND (room.price_cents > ? OR room.price_cents = ? AND room.id > ?) ORDER BY room.price_cents, room.id LIMIT ? OFFSET ?;
--   8   0  SEARCH room USING INDEX ix_room_price_id (price_cents>?)

-- keyset page, row-value seek predicate
EXPLAIN QUERY PLAN SELECT room.* FROM room WHERE (room.price_cents, room.id) > (?, ?) ORDER BY room.price_cents, room.id LIMIT ? OFFSET ?;
--   8   0  SEARCH room USING INDEX ix_room_price_id (price_cents>?)

-- ORDER BY a column with no index
EXPLAIN QUERY PLAN SELECT room.* FROM room ORDER BY room.city, room.id LIMIT ? OFFSET ?;
--   7   0  SCAN room
--  23   0  USE TEMP B-TREE FOR ORDER BY

-- covering index: only indexed columns selected
EXPLAIN QUERY PLAN SELECT room.id, room.price_cents FROM room WHERE room.price_cents > ?;
--   2   0  SEARCH room USING COVERING INDEX ix_room_price_id (price_cents>?)

-- count(*)
EXPLAIN QUERY PLAN SELECT count(*) AS count_1 FROM room;
--   4   0  SCAN room USING COVERING INDEX ix_room_price_id

-- overlap check for one room, index on (room_id, start_date)
EXPLAIN QUERY PLAN SELECT booking.id FROM booking WHERE booking.room_id = ? AND booking.start_date < ? AND booking.end_date > ?;
--   3   0  SEARCH booking USING INDEX ix_booking_room_start (room_id=? AND start_date<?)

-- amenity any(): correlated EXISTS
EXPLAIN QUERY PLAN SELECT room.id FROM room WHERE EXISTS (SELECT 1 FROM amenity, roomamenitylink
  WHERE room.id = roomamenitylink.room_id AND amenity.id = roomamenitylink.amenity_id AND amenity.name = ?) LIMIT ? OFFSET ?;
--   6   0  SCAN room USING COVERING INDEX ix_room_price_id
--   9   0  CORRELATED SCALAR SUBQUERY 1
--  14   9  SEARCH amenity USING COVERING INDEX sqlite_autoindex_amenity_1 (name=?)
--  20   9  SEARCH roomamenitylink USING COVERING INDEX sqlite_autoindex_roomamenitylink_1 (room_id=? AND amenity_id=?)

-- offset page with NO index on price_cents (the script drops ix_room_price_id, the only one)
EXPLAIN QUERY PLAN SELECT room.* FROM room ORDER BY room.price_cents, room.id LIMIT ? OFFSET ?;
--   7   0  SCAN room
--  23   0  USE TEMP B-TREE FOR ORDER BY

In PostgreSQL the same check is EXPLAIN (ANALYZE, BUFFERS), and a keyset page on a matching B-tree shows an Index Scan with an Index Cond on the row value (expected, not run; reading PostgreSQL plans is covered in Query Planning).

Offset vs keyset, measured ​

Median of 7 runs per cell, 20 rows per page, same script, one laptop (real; the shape matters, not the milliseconds):

Depth (rows before the page)OFFSETkeyset, row valuekeyset, naive OR
00.03 ms0.03 ms0.03 ms
1,0000.04 ms0.05 ms0.06 ms
50,0000.57 ms0.04 ms1.10 ms
199,0002.19 ms0.04 ms4.23 ms
199,000, no index on price_cents at all83.43 ms

A second run that also times the bounded-OR predicate (the snippet's default after_key) gave, at depth 199,000: OFFSET 2.41 ms, row value 0.04 ms, bounded OR 0.04 ms, naive OR 4.81 ms; at 50,000: 0.61 / 0.05 / 0.05 / 1.18 ms (real, runs/round2.txt).

Reading: OFFSET grows linearly with the depth because the index entries before the page are walked and discarded; the row-value keyset stays flat because it starts inside the index; the naive OR keyset is the worst of the three because the planner walks the index from the beginning and filters. With no index on price_cents at all (the last row: the script drops the only one), every page sorts the whole table.

Exact errors, warnings and outputs Must-know ​

SituationExact text (real)Where
Unknown query parameter, extra="forbid"{"type":"extra_forbidden","loc":["query","capactiy"],"msg":"Extra inputs are not permitted","input":"2"} → 422curl-run.txt
Paging in a separate dependency next to a forbid modelextra_forbidden for ["query","limit"] and ["query","offset"]first test run
limit too big"type":"less_than_equal" ... "msg":"Input should be less than or equal to 100" → 422curl-run.txt
Tampered cursor{"detail":"Invalid cursor"} → 400curl-run.txt
Cursor value 10**100 without the range checkOverflowError: Python int too large to convert to SQLite INTEGER (a 500 through HTTP)runs/fix1.txt
correlate(Room) with no room in the outer queryno error: FROM review, room inside the subquery, value 4.0runs/fix1.txt
Naive datetime query parameter"type":"timezone_aware" ... "msg":"Input should have timezone info" → 422curl-run.txt
Naive datetime bound through UTCDateTimeStatementError: (builtins.ValueError) naive datetime: pass an aware datetime (UTC)runs/round2.txt
has() on a collectionInvalidRequestError: 'has()' not implemented for collections. Use any().runs/claims.txt
session.exec(sa_select(exists()...)).one()returns (True,), a truthy Row even for "no"first test run
Building objects before adding them, flushing oneSAWarning: Object of type <Booking> not in session, add operation along 'Room.bookings' will not proceedfirst seed version; reproduced in runs/fix1.txt
Filter model available_from aloneValue error, available_from and available_to go together [type=value_error, ...]runs/round2.txt (422 through HTTP: test_unknown_and_out_of_range_parameters_are_422)
SQLite foreign keys offno error at all; orphans remaintest_without_foreign_keys_...
Uvicorn access log"GET /rooms?capactiy=2 HTTP/1.1" 422 Unprocessable Entity, "GET /rooms/feed?cursor=garbage HTTP/1.1" 400 Bad Requestruns/uvicorn.log

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limitation
total = len(rows)count(*) over the filtered subquerypaginate_offsetone integer over the wireone extra query per page
Deep pages slowkeysetpaginate_keyset, row value, (price_cents, id) indexconstant costno page numbers, no total
Pages repeat or skip rowsunique sort + keysetORDER BY ..., idstable under inserts/deleteskey updates still drift; prefer immutable keys
Typos ignoredextra="forbid" modelRoomFilter422 instead of wrong dataone model must hold all params
N+1 in a listselectinload + a count testcount_queriesconstant statementsone test per endpoint
"has X and Y"one any() per valueapply_room_filtercorrect AND semantics, no duplicatesone EXISTS per value
Wrong timesaware in, UTC storedAwareDatetime, UTCDateTimeone meaning per valueTypeDecorator on SQLite
Orphansdatabase ON DELETE + FK enforcementondelete=, PRAGMA listenerholds for every writermust be in migrations
Stale objects after bulk updatesynchronize_sessiondefault 'auto'consistent sessionFalse only for empty sessions
Injectionbound parameters and allow-liststext() + params, Literal sortno SQL from usersnone worth naming

One filter model, one translation function ​

All query parameters of a list endpoint live in one Pydantic model; one function turns it into conditions; the route only orchestrates. Adding a filter is a field plus one if block, and the test suite covers the function without HTTP (test_filters.py) and the endpoint with HTTP (test_api.py).

Offset where people click, keyset where machines read ​

Admin tables keep paginate_offset with a le=10_000 ceiling on offset; feeds, exports and public APIs use paginate_keyset with limit + 1, an opaque validated cursor and an index on the exact key. Both return a typed envelope (Page[T], CursorPage[T]).

Counts and averages in SQL ​

exists() for booleans, func.count() for numbers, group_by/having for reports, a correlated scalar subquery for a value per row on one page, and a precomputed column when a large table is sorted by an aggregate.

Deletes by rule, not by accident ​

Each foreign key gets an explicit ondelete; the ORM mirrors it (cascade_delete, passive_deletes); SQLite gets PRAGMA foreign_keys=ON on every connection; soft delete is chosen per table and enforced centrally with with_loader_criteria.

Choosing ​

SituationRecommendationExtra techniqueReason
Admin table, page numbers neededoffset + totalcap offset, unique sorthumans jump to pages, rarely deep
Infinite scroll, mobile feedkeyset (next_cursor)limit + 1, opaque cursorconstant cost, stable under inserts
Export of millions of rowskeyset batchesLaravel's chunkById() equivalentnever re-reads earlier rows
"Results: 12,345" on a huge tableestimate or no totalcache the countexact count can cost more than the page
Filter on child rowsany() / has()index on the child FKEXISTS, no duplicates
Load children of a pageselectinloadquery-count test2 statements
Load only matching childrenjoin + contains_eagerpopulate_existingone statement, filtered collection
Per-row computed value on a pagecorrelated scalar subqueryindex the inner FKsimple, page-sized cost
Report over all rowsgroup_by + havingouterjoin to keep empty parentsone pass
Calendar availabilityhalf-open overlap + NOT EXISTSPostgreSQL exclusion constraintcorrect for all overlap shapes
Child must die with parentON DELETE CASCADE (+ passive_deletes)ORM cascade for small collectionssurvives bulk deletes and other writers
Optional referenceON DELETE SET NULLpassive_deletes=Truekeeps history
Undo / retentionsoft deletewith_loader_criteria, partial unique indexhistory kept
Raw SQL neededtext() with named paramsallow-list identifierssafe and explicit

ORM expressions vs text() vs a query builder ​

NeedSQLAlchemy expressionstext()Go sqlcGo squirrel
Dynamic filtersnatural (and_(*conds))string assembly, riskyone query per shape, or sqlc.narg tricksnatural (Where(sq.Eq{...}))
Type safetyruntime + mypy with col()nonegenerated, compile-timenone
Vendor SQL (window, CTE)most supportedeverythingeverything the parser knowsstrings
Injection safetyautomaticwith :paramsautomaticautomatic placeholders
ReviewabilityPythonSQLSQL filesGo builder chains

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

All of this page runs inside one FastAPI process with one SQLAlchemy engine: filter model → apply_room_filter → one session → two statements. The simplest correct setup is exactly the snippet: one composite index per sort option, foreign keys with ondelete, aware timestamps, a query-count test per list endpoint. Example: the rooms API on one PostgreSQL instance serves GET /rooms with an offset envelope for the admin UI and GET /rooms/feed with a cursor for the mobile app, from the same table and the same (price_cents, id) index.

Modular monolith and multiple databases ​

When bookings and catalogue become modules with their own schemas, cross-module filters ("rooms free between two dates") stop being one NOT EXISTS. Either the catalogue module asks the booking module for booked room ids for the range (one call, then ~col(Room.id).in_(ids)) or a read model joins both. Cascades across module boundaries become events: the catalogue publishes RoomRetired, the booking module decides whether to cancel or keep bookings; a database ON DELETE CASCADE across modules would couple them. Soft delete is common at the boundary because other modules still reference the id.

Microservices ​

Across services there is no join, no EXISTS and no foreign key. A search service owns a denormalised index (rooms with city, price, amenities, average rating and a set of booked date ranges), fed by events from the room and booking services, and serves filters and keyset pages from it. Example flow: BookingCreated{room_id, start, end} → search service updates the room's availability → GET /search?from=...&to=... filters there. Counts become approximate, cursors must encode the search engine's sort values, and deletes are tombstone events consumed idempotently. The API envelope (items, next_cursor) stays the same, which is the point of defining it carefully now.

Distributed data: replicas, caches, sharded databases, multi-region ​

Read replicas serve list endpoints well, with lag: a booking made a second ago may still show the room as free on the replica, so the final availability check runs on the primary inside the booking transaction. Cached first pages (GET /rooms?city=Tabriz, no cursor) are safe for seconds; deep offset pages are not worth caching. Keyset cursors survive replicas because they carry the key, not a position. With sharding by city or tenant, a cross-shard list is a merge of per-shard keyset pages ordered by the same key; offset across shards would require reading offset + limit rows from every shard. In multi-region setups, store UTC everywhere; local time is a presentation concern.

Scaling path: 1×, 10×, 100× ​

LoadWhat changes
1× (thousands of rooms)the snippet as is; offset everywhere is fine; counts exact
10× (hundreds of thousands)keyset for feeds and exports; composite indexes per sort; offset ceiling; query-count tests in CI; EXPLAIN in code review
100× (tens of millions, many tenants)no exact totals; precomputed aggregates (rating, booking count) maintained on write; full-text or a search service for text filters; read replicas for lists; partitioned booking table by date; archive or hard-delete old soft-deleted rows

Lab ​

All commands run from docs/snippets/python/queries-pagination-aggregation/. Outputs marked "real" were produced on CPython 3.9.6 (macOS) with the pinned versions and SQLite 3.54.0, and are saved under pipeline/sources/queries-pagination-aggregation/runs/. Python 3.12 with current releases was not run (unverified): expect different version numbers and possibly different statement texts. PostgreSQL steps are "expected, not run".

1. Install and run the tests (real) ​

uv venv ~/venvs/queries --python python3                       # keep the venv outside the repository
uv pip install --python ~/venvs/queries/bin/python -r requirements.lock
PYTHONDONTWRITEBYTECODE=1 ~/venvs/queries/bin/python -m pytest
# 60 passed in 0.91s       (runs/lab-steps.txt; the dev venv: runs/pytest-v.txt)

The tests import app through pythonpath = ["."] in pyproject.toml, so the project itself does not need to be installed. Installing it in place (uv pip install '.[test]' run inside this directory) also passes, but leaves build/ and queries_pagination_aggregation.egg-info/ behind in the snippet directory (real, scratch copy): install from a copy if you want the package. Plain pip works the same way: python3 -m venv ~/venvs/piplock && ~/venvs/piplock/bin/pip install -r requirements.lock, then pytest → 60 passed in 0.87s (real). On Python 3.12 with uv's project workflow: uv sync --extra test && uv run pytest (expected, not run).

2. Watch the SQL (real) ​

PYTHONDONTWRITEBYTECODE=1 ~/venvs/queries/bin/python -m app.echo_demo

Expect the twelve steps of The SQL the snippets emit: the count over the filtered subquery, the seek predicate with (9000, 9000, 9000, 1, 3, 0), DESC NULLS LAST, the three statements of exists/count/len, GROUP BY ... HAVING, LEFT OUTER JOIN, two EXISTS forms, the two bulk UPDATEs (only the 'fetch' one with RETURNING id), the cascade sequence and the bound LIKE ?.

3. Read the plans and time the pages (real) ​

PYTHONDONTWRITEBYTECODE=1 ~/venvs/queries/bin/python -m app.explain_demo           # 200,000 rooms; 1.58 s wall time on the build laptop (real)
PYTHONDONTWRITEBYTECODE=1 ~/venvs/queries/bin/python -m app.explain_demo 20000     # smaller, faster

Expect SCAN room USING INDEX ix_room_price_id for OFFSET and the naive OR, SEARCH ... (price_cents>?) for the row value and the bounded OR, USE TEMP B-TREE FOR ORDER BY for city and for the dropped index, and the timing table of Offset vs keyset, measured. Then edit after_key in app/pagination.py to return after_key_naive(...) and rerun pytest -k keyset. Real (scratch copy, runs/lab-steps.txt): 1 failed, 3 passed, the assertion that the SQL contains room.price_cents >= ? AND (...) fails, which is the point of asserting the predicate.

4. See page drift with your own eyes (real) ​

PYTHONDONTWRITEBYTECODE=1 ~/venvs/queries/bin/python -m pytest -k "between_pages" -rA

Real: test_insert_between_pages_duplicates_with_offset_not_with_keyset and test_delete_between_pages_skips_with_offset pass, which means offset page 2 showed the Garden twice after an insert and never showed the Courtyard after a delete, while keyset page 2 was right both times.

5. Call the API (real) ​

PYTHONDONTWRITEBYTECODE=1 ~/venvs/queries/bin/uvicorn app.main:app --port 18933
curl -s 'localhost:18933/rooms'
curl -s 'localhost:18933/rooms?capactiy=2'
curl -s 'localhost:18933/rooms?limit=1000'
curl -s 'localhost:18933/rooms/feed?cursor=garbage'
curl -s 'localhost:18933/bookings/recent?since=2026-11-22T10:00:00'
curl -s 'localhost:18933/bookings/recent?since=2026-11-22T13:30:00%2B03:30'

Real (runs/curl-run.txt, runs/uvicorn.log): {"items":[],"total":0,"limit":20,"offset":0} (the app starts with an empty in-memory database), 422 extra_forbidden, 422 less_than_equal, 400 Invalid cursor, 422 timezone_aware, and [] with 200. Uvicorn logged "GET /rooms?capactiy=2 HTTP/1.1" 422 Unprocessable Entity.

6. Break it on purpose (real) and PostgreSQL (expected, not run) ​

Remove selectinload(Room.bookings) from rooms_with_bookings in app/main.py and run pytest -k query_count: the assertion small.count == big.count == 2 fails with assert 3 == 6: 1 + 2 statements for limit=2, 1 + 5 for limit=100 (real, scratch copy, runs/lab-mutation.txt). Remove the event.listen(engine, "connect", _fk_on) line and run pytest -k cascade. Real (scratch copy, runs/lab-steps.txt): 3 failed, 8 passed; the bulk delete leaves orphans, session.delete(garden) leaves its reviews (7 instead of 5, because passive_deletes="all" trusted a cascade that never fired), and the user delete no longer sets user_id to NULL (assert 2 is None). On PostgreSQL (expected, not run): install a driver (psycopg), then TEST_DATABASE_URL=postgresql+psycopg://app:app@localhost:5432/rooms_test pytest -m "not sqlite_only". The engine fixture reads TEST_DATABASE_URL (default sqlite://) and drops the tables after each test; the 16 tests marked sqlite_only assert SQLite's SQL text, plans or storage and are skipped there, leaving 44 portable ones (real on SQLite: -m "not sqlite_only" → 44 passed, 16 deselected, runs/pytest-portable.txt). Expect native ILIKE, timestamptz keeping offsets correct without the TypeDecorator, NULLS FIRST as the default for DESC, and EXPLAIN showing an Index Scan for the keyset page (expected, not run).

For PHP/Laravel developers ​

Laravel's query builder and Eloquent cover the same ground with different names. paginate(15) is the offset envelope with a total; the docs: "The paginate method counts the total number of records matched by the query before retrieving the records from the database." simplePaginate() skips that count ("if you only need to display simple "Next" and "Previous" links ... you may use the simplePaginate method to perform a single, efficient query"), and cursorPaginate() is keyset pagination: "Your query must contain an "order by" clause in order to take advantage of cursor pagination", and it "requires that the ordering is based on at least one unique column or a combination of columns that are unique. Columns with null values are not supported." The docs' own comparison is the same pair of queries as this page: select * from users order by id asc limit 15 offset 15; vs select * from users where id > 15 order by id asc limit 15;. whereHas('amenities', fn) is any(), whereDoesntHave is ~any(), whereBelongsTo/whereHas on a belongs-to is has(), withCount('bookings') and withAvg('reviews', 'rating') are the correlated scalar subqueries of Scalar and correlated subqueries, chunkById(200, fn) is keyset batching ("If you are filtering the results of the chunk method based on a column that you will also be updating while iterating over the results, you should use the chunkById method"), the SoftDeletes trait is the global filter of Soft delete, and cascadeOnDelete() / nullOnDelete() / restrictOnDelete() in a migration are ondelete="CASCADE" / "SET NULL" / "RESTRICT". Bound parameters are the default in both; DB::raw() and whereRaw() are the text() of Laravel and need the same care.

php
// RoomController@index (Laravel 13): the snippet's GET /rooms and /rooms/feed in Eloquent
$validated = $request->validate([
    'city' => ['array'], 'city.*' => ['string'],
    'min_capacity' => ['integer', 'min:1', 'max:50'],
    'amenity' => ['array'], 'amenity.*' => ['string'],
    'sort' => ['in:price,-price,name,rating'],                      // the Literal sort key
]);

$query = Room::query()
    ->when($validated['city'] ?? null, fn ($q, $cities) => $q->whereIn('city', $cities))                  // in_()
    ->when($validated['min_capacity'] ?? null, fn ($q, $n) => $q->where('capacity', '>=', $n))
    ->when($validated['amenity'] ?? [], function ($q, $names) {
        foreach ($names as $name) {                                                                          // one any() per value
            $q->whereHas('amenities', fn ($a) => $a->where('name', $name));
        }
    })
    ->whereDoesntHave('bookings', fn ($b) => $b->where('start_date', '<', $to)->where('end_date', '>', $from)) // NOT EXISTS overlap
    ->withCount('bookings')->withAvg('reviews', 'rating')                                                   // correlated subqueries
    ->orderBy('price_cents')->orderBy('id');                                                                // unique tie-breaker

$page = $query->paginate(20);            // offset + total: {data, total, per_page, current_page, ...}
$feed = $query->cursorPaginate(20);      // keyset: {data, next_cursor, prev_cursor, ...}

Room::where('city', 'Tabriz')->chunkById(500, fn ($rooms) => $rooms->each->touch());  // keyset batches
Laravel 13This page (SQLAlchemy / SQLModel / FastAPI)
paginate(20)paginate_offset + Page[T] (count + page)
simplePaginate(20)offset without the count (limit + 1)
cursorPaginate(20)paginate_keyset + CursorPage[T]
whereHas / whereDoesntHaveany() / ~any()
whereBelongsTo, whereRelationhas(), any(cond)
withCount, withAvgcorrelated scalar_subquery() with func.count / func.avg
chunk / chunkByIdoffset batches / keyset batches
SoftDeletes, withTrashed()SoftDeleteSession, execution_options(include_deleted=True)
cascadeOnDelete(), nullOnDelete()ondelete="CASCADE", ondelete="SET NULL"
$request->validate([...])Annotated[RoomFilter, Query()] with extra="forbid"
Model::preventLazyLoading()raiseload("*"), query-count tests

The Go angle ​

Go services write this layer without an ORM. With sqlc ("sqlc generates fully type-safe idiomatic Go code from SQL") you write each query once in SQL and get a typed function: "You write SQL queries", "You run sqlc to generate Go code that presents type-safe interfaces to those queries", "You write application code that calls the methods sqlc generated". Fixed-shape queries (the keyset page, the overlap check, the city report) fit sqlc perfectly; list filters with many optional fields are awkward, because each SQL text is fixed at generate time, so teams either write one query with sqlc.narg()-style nullable parameters (WHERE (sqlc.narg('city')::text IS NULL OR city = sqlc.narg('city'))) or switch to a builder. Squirrel is that builder: "Squirrel is not an ORM." "Squirrel helps you build SQL queries from composable parts", with sq.Eq given a nil value for IS NULL and a slice for IN (see the code block), and PlaceholderFormat(sq.Dollar) for PostgreSQL's $1 placeholders; values always become arguments, never SQL text. There is no synchronize_session because there is no session, and no ORM cascade: the database's ON DELETE is the only rule, which is the same conclusion this page reaches. The connection and transaction side is in database/sql and pgx.

go
// Go: the snippet's filter + keyset page with squirrel and pgx v5 (illustrative, not compiled here)
func ListRooms(ctx context.Context, pool *pgxpool.Pool, f RoomFilter, after *Cursor, limit uint64) ([]Room, *Cursor, error) {
	q := sq.Select("id", "name", "city", "capacity", "price_cents").From("room").
		Where(sq.Eq{"deleted_at": nil}).PlaceholderFormat(sq.Dollar)
	if len(f.Cities) > 0 {
		q = q.Where(sq.Eq{"city": f.Cities}) // city IN ($1, $2)
	}
	for _, name := range f.Amenities { // one EXISTS per amenity, like any()
		q = q.Where(sq.Expr(`EXISTS (SELECT 1 FROM roomamenitylink l JOIN amenity a ON a.id = l.amenity_id
			WHERE l.room_id = room.id AND a.name = ?)`, name))
	}
	if after != nil {
		q = q.Where(sq.Expr("(price_cents, id) > (?, ?)", after.Price, after.ID)) // row-value seek
	}
	sql, args, err := q.OrderBy("price_cents", "id").Limit(limit + 1).ToSql()
	if err != nil {
		return nil, nil, err
	}
	rows, err := pool.Query(ctx, sql, args...)
	if err != nil {
		return nil, nil, err
	}
	items, err := pgx.CollectRows(rows, pgx.RowToStructByName[Room])
	if err != nil || uint64(len(items)) <= limit {
		return items, nil, err
	}
	last := items[limit-1]
	return items[:limit], &Cursor{Price: last.PriceCents, ID: last.ID}, nil
}
GoThis page
sqlc query file + generated methoda fixed select() in queries.py
sqlc.narg() optional parameterif f.city: conditions.append(...)
squirrel sq.Eq, sq.Expr, ToSql()where(), and_(), text() with params
PlaceholderFormat(sq.Dollar)the dialect chooses ? or %(name)s / $1
explicit SELECT count(*)paginate_offset
(price_cents, id) > ($1, $2)tuple_(...) > tuple_(...)
ON DELETE onlyORM cascade + ON DELETE

Common misconceptions ​

BeliefReality
OFFSET skips rows cheaplyskipped rows are produced and discarded; 2.19 ms at depth 199,000 vs 0.04 ms keyset (real)
Keyset is WHERE id > ?only when sorting by id; otherwise the full key (sort columns, id)
Keyset never repeats rowsit does when a key column is updated between pages (real); prefer immutable keys
.correlate(Room) fails if room is missingit silently adds room to the subquery's FROM (real)
update(...).limit(n) batches a bulk updateupdate()/delete() have no .limit(); select bounded ids first
Any correct seek predicate is fastthe naive OR form was a SCAN and slower than OFFSET in SQLite (real)
ORDER BY price is deterministicties have no order; always end with a unique column
NULLs sort the same everywheresmallest in SQLite, largest in PostgreSQL; write nulls_last()
len(rows) is a countit transfers and builds every row
count() > 0 is as good as exists()EXISTS stops at the first row
session.exec(select(exists())).one() is a boolwith a SQLAlchemy select it is a Row, always truthy; use session.scalar() (real)
A join filter narrows room.bookingsselectinload loads all children; contains_eager loads the filtered ones (real)
in_(["wifi", "kitchen"]) means bothit means either; one any() per required value
between finds overlapping bookingsit is inclusive and tests one column; use half-open overlap
DateTime(timezone=True) keeps offsets on SQLitethe offset is dropped without conversion (real)
Bulk delete() runs ORM cascadesonly the database's ON DELETE runs (real)
SQLite enforces foreign keysonly after PRAGMA foreign_keys=ON on each connection
Soft delete is invisible to bulk DMLbulk update() changed the soft-deleted Attic too (real)
extra="forbid" checks only its own fieldsit sees every query parameter, including other dependencies' (real)
Bound parameters protect identifiersplaceholders carry values only; allow-list sort columns
autoescape is about SQL injectionit is about % and _ wildcards inside LIKE patterns

Cheat sheet ​

TopicWhat to remember
Filtersone model, one apply_*_filter, and_(*conditions)
Query modelsAnnotated[Model, Query()], extra="forbid", paging inside the model, FastAPI 0.115+
Texticontains(q, autoescape=True); ASCII-only case folding on SQLite
Listsin_(); empty list returns nothing
NULLis_(None), nulls_last() explicitly
Sortend with the primary key; Literal sort keys
Offsetlimit/offset, bounded; count over order_by(None).subquery()
Keyset(sort, id) > (?, ?) or bounded OR; limit + 1; opaque cursor, int64-checked; 400 on bad cursor; immutable key for exports
Indexcolumns in sort order; equality columns first; covering when possible
PlansEXPLAIN QUERY PLAN (SQLite), EXPLAIN (ANALYZE, BUFFERS) (PostgreSQL); SEARCH good, TEMP B-TREE = sort
Booleanssession.scalar(select(exists().where(...)))
Countsfunc.count() in SQL, count(col) skips NULLs
Per-row valuescorrelated scalar_subquery() with .correlate() and .label()
ReportsWHERE before grouping, HAVING after, outerjoin keeps empty parents
Related filtersany() collections, has() many-to-one, contains(obj)
Dateshalf-open [start, end), overlap a.start < b.end AND a.end > b.start
Time zonesAwareDatetime in, UTC stored, TypeDecorator on SQLite
Bulkupdate()/delete() one statement; synchronize_session='auto'; // for integers
Cascadesondelete in the database, cascade_delete / passive_deletes in the ORM, FK pragma on SQLite
N+1before_cursor_execute counter; assert constant counts at two page sizes

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why does OFFSET pagination get slower on deep pages, and what replaces it? Must-know ​

Answer

Answer: The database must produce and discard every row before the offset ("The rows skipped by an OFFSET clause still have to be computed inside the server"), so the cost grows with the page number; the snippet measured 2.19 ms at depth 199,000 against 0.03 ms at depth 0. Keyset (seek) pagination remembers the last sort key and asks for rows after it, WHERE (price_cents, id) > (?, ?) ORDER BY price_cents, id LIMIT 21, which costs the same on every page (0.04 ms) and is stable under inserts and deletes. The price is no page numbers and no total. See Keyset pagination.

2 — Your keyset predicate is price > ? OR (price = ? AND id > ?) and the page is still slow. Why, and how do you fix it? Must-know ​

Answer

Answer: Many planners cannot turn that OR into an index range, so they walk the index from the start and filter: SQLite showed SCAN room USING INDEX ix_room_price_id and 4.23 ms at depth 199,000, slower than OFFSET. Either use a row-value comparison (price_cents, id) > (?, ?) (PostgreSQL, SQLite 3.15+), or keep the OR and add the redundant bound price_cents >= ? in front; both gave SEARCH ... (price_cents>?) and 0.04 ms. Check with EXPLAIN QUERY PLAN. See Indexes behind ORDER BY.

3 — Why must every paginated order_by end with a unique column? Must-know ​

Answer

Answer: Rows with equal sort values have no defined order, and the planner may pick different plans for different LIMIT/OFFSET values, so two rooms at 9000 can swap between requests and one appears on two pages while the other disappears. PostgreSQL's docs warn that without a unique ORDER BY "you will get an unpredictable subset of the query's rows." Keyset pagination additionally needs a unique key to define "after". The snippet sorts by (price_cents, id).

4 — What is the difference between exists(), func.count() and len() for "does this room have bookings"? Must-know ​

Answer

Answer: select(exists().where(...)) returns one boolean and stops at the first match; func.count() returns one integer but must find every match; len(session.exec(select(Booking)...).all()) transfers and builds every row in Python. All three give the same answer on six rows; only the first scales. With SQLModel, run the exists query through session.scalar(): session.exec(sa_select(exists()...)).one() returns a Row like (True,), which is always truthy.

5 — How do you find rooms that are free between two dates, and why not between? Must-know ​

Answer

Answer: With half-open ranges [start, end), a booking overlaps the request when booking.start_date < :end AND booking.end_date > :start; a free room is NOT EXISTS such a booking for that room. That one rule covers partial overlap, containment both ways and back-to-back stays (Dec 4 to Dec 10 is free between bookings ending Dec 4 and starting Dec 10). between is inclusive on both ends and tests a single column, so it misses containing ranges and blocks the checkout day. See Date ranges.

6 — A filter ?amenity=wifi&amenity=kitchen must return rooms with both. How do you write it, and what goes wrong with a join? Important ​

Answer

Answer: One col(Room.amenities).any(Amenity.name == name) per value, combined with AND: two correlated EXISTS subqueries, no duplicate rows. A join with Amenity.name.in_([...]) means wifi OR kitchen and returns a room once per matching amenity, so it needs distinct() and still has the wrong meaning; "both" would require GROUP BY room.id HAVING count(DISTINCT amenity.name) = 2.

7 — You filter rooms with a join on Alice's bookings and add selectinload(Room.bookings). What is in room.bookings? Important ​

Answer

Answer: All bookings of each matched room, including Bob's: the join chooses the rooms, the loader option runs a separate SELECT ... WHERE booking.room_id IN (...) without your filter. To load only the joined, filtered rows into the collection use contains_eager(Room.bookings) on the joined statement (one statement), and populate_existing=True if the room may already be in the identity map with its full collection.

8 — What does synchronize_session control in a bulk update(), and which value do you use? Important ​

Answer

Answer: Whether objects already loaded in the session see the change. 'evaluate' applies the WHERE in Python to loaded objects, 'fetch' gets the affected primary keys via RETURNING or a SELECT, False does nothing (the Garden stayed at 9000 after the UPDATE set 9900, real), and the default 'auto' tries 'evaluate' and falls back to 'fetch' (per the 2.0.58 source and the run; the docs page describes it the other way round). Keep 'auto'; use False only where the session holds no affected objects. Bulk statements never run ORM cascades.

9 — When do you use cascade_delete=True, ondelete="CASCADE" and passive_deletes, and what happens on SQLite without the pragma? Important ​

Answer

Answer: ondelete="CASCADE" puts the rule in the database so it holds for bulk deletes and every other writer; cascade_delete=True ("all, delete-orphan") makes session.delete(parent) load and delete children through the ORM, with events; passive_deletes tells the ORM to leave unloaded children to the database. SQLite enforces foreign keys only after PRAGMA foreign_keys=ON per connection: without it, the snippet's bulk delete left 3 bookings and 3 reviews orphaned with no error.

10 — Why does DateTime(timezone=True) not protect you on SQLite, and what does the snippet do instead? Important ​

Answer

Answer: SQLite has no date/time storage class; SQLAlchemy stores an ISO string and drops the offset without converting, so 13:30+03:30 comes back as naive 13:30 (real). The snippet's UTCDateTime TypeDecorator rejects naive values, converts aware ones to UTC before binding and attaches UTC when reading, and the API accepts only AwareDatetime, so ?since=2026-11-22T10:00:00 is a 422. On PostgreSQL, timestamptz stores UTC itself.

11 — How do you prove in CI that a list endpoint has no N+1? Good to know ​

Answer

Answer: Register a before_cursor_execute listener on the engine for the duration of the request (the snippet's count_queries), call the endpoint with two page sizes, and assert the same small number of statements, here 2 for limit=2 and limit=100, plus that the second statement contains IN (. The Before endpoint measured 1 + N. raiseload("*") in development complements it.

12 — How do Laravel's paginate(), cursorPaginate(), whereHas and withCount map to this page, and what does a Go service use? Good to know ​

Answer

Answer: paginate() is the offset envelope with a count, simplePaginate() skips the count, cursorPaginate() is keyset pagination with the same unique, non-null ordering rule; whereHas is any(), withCount/withAvg are correlated scalar subqueries, chunkById is keyset batching. In Go, sqlc generates typed functions from fixed SQL (good for keyset pages and reports) and squirrel builds dynamic filters with placeholders; neither has a session or ORM cascade, so ON DELETE is the only delete rule.

Glossary ​

TermMeaning
selectSQLAlchemy 2.0's statement constructor for every query (select(Room), select(Room.name, func.count()))
whereAdds conditions to a statement, ANDed together
and_ / or_ / not_Boolean combinators for SQL expressions (&, |, ~)
in_IN (...) with one bound parameter per value; empty list returns nothing
like / ilikePattern matching; ilike ignores case (lower(...) LIKE lower(?) on SQLite)
contains / icontainsLIKE '%' || ? || '%'; with autoescape=True wildcards in the value are literal; on relationships, contains(obj) tests membership
is_IS NULL / IS comparison
order_by / descSort clause and descending modifier
nulls_lastNULLS LAST modifier; default NULL placement differs by database
limit / offsetPage size and number of rows skipped
Offset paginationPages by position (LIMIT ? OFFSET ?), with page numbers and total
Keyset paginationPages by the last seen sort key (WHERE key > last), constant cost
Cursor paginationKeyset pagination with the key encoded in an opaque next_cursor token
Seek methodMarkus Winand's name for keyset pagination
Row valueA tuple comparison like (price_cents, id) > (?, ?); tuple_() in SQLAlchemy
Tie-breakerA unique last sort column that makes the order deterministic
Pagination envelopeThe response shape around items: items, total, limit, offset or next_cursor
totalNumber of rows matching the filter, from a count(*) over the filtered subquery
next_cursorOpaque token for the next keyset page; null on the last page
exists / select existsEXISTS (subquery); select(exists().where(...)) returns one boolean
count / func.countcount(*) or count(column) in SQL, as opposed to len() in Python
scalar_subqueryA subquery returning one value, usable as a column or in WHERE/ORDER BY
Correlated subqueryA subquery that refers to the outer row (review.room_id = room.id)
func.avgSQL avg(); None for an empty group
group_by / havingGrouping clause and group filter (after aggregation)
labelAS name for a column expression; usable in order_by
aggregateA function over many rows: count, sum, avg, min, max
join / outerjoinINNER JOIN / LEFT OUTER JOIN in a statement
selectinload for filtersThe trap: a loader option loads all children regardless of the join filter
contains_eagerFills a relationship from columns already joined in the statement
relationship filterA WHERE condition on related rows, via any()/has() or a join
any / hasRelationship EXISTS helpers: any() for collections, has() for many-to-one
date range overlapa.start < b.end AND a.end > b.start for half-open ranges
Half-open interval[start, end): includes start, excludes end; back-to-back ranges do not overlap
betweenx BETWEEN a AND b, inclusive on both ends
timezone-aware datetimeA datetime with tzinfo; an instant, comparable across zones
DateTime(timezone=True)SQLAlchemy type requesting a zone-aware column (timestamptz on PostgreSQL); offset dropped on SQLite
AwareDatetimePydantic type that "Requires the input to have a timezone"
TypeDecoratorSQLAlchemy hook to convert values on bind and on result (the snippet's UTCDateTime)
bulk update / bulk deleteOne UPDATE/DELETE statement for many rows via update()/delete()
synchronize_sessionHow a bulk statement updates loaded objects: 'auto', 'evaluate', 'fetch', False
cascade all delete-orphanORM cascade "all, delete-orphan": delete children with the parent or when removed from the collection; SQLModel cascade_delete=True
ondelete CASCADEForeign-key action that deletes child rows in the database; Field(ondelete="CASCADE")
SET NULL / RESTRICT / NO ACTIONOther foreign-key actions: null the reference, forbid the delete, check at statement end (default)
passive_deletesTells the ORM to rely on the database's ON DELETE instead of loading children (True or "all")
soft deleteMarking a row deleted (deleted_at) instead of removing it
with_loader_criteriaOption that adds a condition to every load of an entity; used in a do_orm_execute event
filter modelA Pydantic model holding a list endpoint's query parameters
Query parametersURL ?key=value pairs; repeated keys become lists
Depends filterA dependency class/function that collects filter parameters (Depends()), the alternative to a query model
extra="forbid"Pydantic config that rejects unknown fields; on a query model, unknown query parameters
N+1 in list endpoint1 query for the page plus 1 per row for a lazy relationship
query countNumber of statements a request sends, measured in tests
event listenerA function registered with event.listen() on an engine, session or mapper
before_cursor_executeEngine event fired before each statement is executed on a DBAPI cursor
EXPLAIN QUERY PLANSQLite command that shows how a statement will be executed (SCAN, SEARCH, TEMP B-TREE)
index for order byAn index whose leading columns match the ORDER BY, so no sort is needed
covering indexAn index containing every column the query needs; USING COVERING INDEX
bound parametersValues sent separately from SQL text (?, :name, $1)
SQL injectionUser input changing the SQL statement itself
text()SQLAlchemy construct for literal SQL with :name bind parameters
EloquentLaravel's ORM; paginate, cursorPaginate, whereHas, withCount, chunk
paginate / cursorPaginateLaravel offset pagination with total / keyset pagination
whereHas / withCountLaravel relationship EXISTS filter / correlated count column
chunkLaravel batch processing (chunk by offset, chunkById by key)
sqlcGo tool that generates typed code from SQL queries
squirrelGo SQL query builder ("Squirrel is not an ORM")

References ​

Built by Morteza Negahi