Databases · Intermediate · 22 min
Choose between an ORM, a query builder and raw SQL
By Padding · Updated 18 Nov 2026
Debian 13 (postgres:18 image) · PostgreSQL 18.7 · Python 3.15 · SQLAlchemy 2.1 · psycopg 3.3
You will write the same lookup, report and bulk update with the SQLAlchemy ORM, SQLAlchemy Core and raw psycopg, read the SQL each one sends, fix an N+1 query and time the update, so you can pick the right layer for each query in your own project.
On this page
Arguments about ORMs tend to be settled by taste. This tutorial settles them with evidence from your own terminal instead. You write three queries that every app ends up needing (a lookup by a unique field, a report that joins two tables and groups the result, and an update that touches thousands of rows) and you write each of them three times:
- with the SQLAlchemy ORM, where rows become Python objects and relationships become attributes
- with SQLAlchemy Core, a query builder: you compose SQL from Python expressions and get plain rows back
- as raw SQL strings sent through psycopg, the driver underneath both
Along the way you read the SQL the ORM generates, cause the N+1 problem on purpose and fix it, and time the bulk update four ways. The data is a small courier firm: 200 riders in four cities and 40,000 deliveries. The tutorial ends with a guide for choosing per query, not a single winner, because most real projects use more than one of these layers.
The commands use SQLAlchemy 2.1, psycopg 3.3, Python 3.15 and PostgreSQL 18. PostgreSQL 19 came out in November 2026, and everything here works the same on it.
Step 1 · Create the database and the project
Create a login role for the app; --pwprompt asks for its password twice so it stays out of your shell history:
sudo -u postgres createuser --pwprompt courierappCreate a database owned by that role, and a private ~/.pgpass file for the password. If you already have a ~/.pgpass, skip the install line and add to the existing file:
sudo -u postgres createdb --owner=courierapp courier
install -m 600 /dev/null ~/.pgpassOpen ~/.pgpass in your editor and add this line, replacing the last field with the password you chose:
localhost:5432:courier:courierapp:the-password-you-choseThe connection string carries no password. psycopg (through libpq) finds it in ~/.pgpass, and SQLAlchemy passes the same details to psycopg, so both read the one file:
export DATABASE_URL="postgresql://courierapp@localhost:5432/courier"Create the project and add both libraries. The ranges accept patch releases and nothing newer:
mkdir -p ~/orm-demo
cd ~/orm-demo
uv init --no-package --python 3.15
uv add "sqlalchemy>=2.1,<2.2" "psycopg[binary]>=3.3,<3.4"Now write the schema and the data. generate_series builds every row inside PostgreSQL, so the load is quick and the numbers are the same on every machine:
cat > schema.sql <<'SQL'
CREATE TABLE riders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL UNIQUE,
city text NOT NULL
);
CREATE TABLE deliveries (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
rider_id bigint NOT NULL REFERENCES riders (id),
fee numeric(10, 2) NOT NULL CHECK (fee > 0),
status text NOT NULL CHECK (status IN ('pending', 'delivered', 'archived')),
delivered_on date NOT NULL
);
CREATE INDEX deliveries_rider_id_idx ON deliveries (rider_id);
INSERT INTO riders (name, city)
SELECT 'Rider ' || lpad(n::text, 3, '0'),
(ARRAY['Lagos', 'Nairobi', 'Accra', 'Kigali'])[1 + n % 4]
FROM generate_series(1, 200) AS n;
INSERT INTO deliveries (rider_id, fee, status, delivered_on)
SELECT 1 + n % 200,
1000 + (n % 50) * 100,
CASE WHEN n % 10 = 0 THEN 'pending' ELSE 'delivered' END,
date '2025-01-01' + n % 700
FROM generate_series(1, 40000) AS n;
SQL
psql "$DATABASE_URL" -X -v ON_ERROR_STOP=1 -q -f schema.sqlCheck it worked
Count the rows:
psql "$DATABASE_URL" -X -Atc "SELECT (SELECT count(*) FROM riders), (SELECT count(*) FROM deliveries);"It prints 200|40000. Then check the libraries:
uv run python -c "import sqlalchemy, psycopg; print(sqlalchemy.__version__, psycopg.__version__)"It prints something like 2.1.9 3.3.9.
Step 2 · Map the tables for SQLAlchemy
The ORM needs a Python class per table. Write them in models.py, along with the engine that every SQLAlchemy script in this project shares:
cat > models.py <<'PY'
import os
from datetime import date
from decimal import Decimal
from sqlalchemy import ForeignKey, Numeric, create_engine
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
# SQLAlchemy names the driver in the URL scheme: postgresql+psycopg means psycopg 3.
url = os.environ["DATABASE_URL"].replace("postgresql://", "postgresql+psycopg://", 1)
engine = create_engine(url, echo=os.environ.get("SQL_ECHO") == "1")
class Base(DeclarativeBase):
pass
class Rider(Base):
__tablename__ = "riders"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]
city: Mapped[str]
deliveries: Mapped[list["Delivery"]] = relationship(back_populates="rider")
class Delivery(Base):
__tablename__ = "deliveries"
id: Mapped[int] = mapped_column(primary_key=True)
rider_id: Mapped[int] = mapped_column(ForeignKey("riders.id"))
fee: Mapped[Decimal] = mapped_column(Numeric(10, 2))
status: Mapped[str]
delivered_on: Mapped[date]
rider: Mapped[Rider] = relationship(back_populates="deliveries")
PYThree things to notice:
- The schema came from
schema.sql, not from these classes. The classes describe tables that already exist. In a real project, a migration tool such as Alembic owns the schema, and the models must match it. relationship()gives eachRideradeliverieslist and eachDeliveryarider. Neither is a column: SQLAlchemy loads them with extra queries, which matters in a later step.- Every mapped class carries a Core
Tableobject atRider.__table__. The Core versions below use those tables directly. A project with no ORM at all would declareTable(...)objects instead, or read them from the database withMetaData.reflect().
Setting SQL_ECHO=1 turns on echo, which logs every statement the engine sends.
Check it worked
uv run python -c "from models import Rider, Delivery; print(Rider.__table__.c.keys(), Delivery.__table__.c.keys())"It prints the column names of both tables, ['id', 'name', 'city'] first. No connection is made yet: create_engine connects on first use.
Step 3 · Look up one rider three ways and read the SQL
Write lookup.py with one function per approach. Each returns the rider's name and city:
cat > lookup.py <<'PY'
import os
import psycopg
from sqlalchemy import select
from sqlalchemy.orm import Session
from models import Rider, engine
NAME = "Rider 004"
def orm():
with Session(engine) as session:
rider = session.scalars(select(Rider).where(Rider.name == NAME)).one()
return (rider.name, rider.city)
def core():
riders = Rider.__table__
with engine.connect() as conn:
row = conn.execute(
select(riders.c.name, riders.c.city).where(riders.c.name == NAME)
).one()
return tuple(row)
def raw():
with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
return conn.execute(
"SELECT name, city FROM riders WHERE name = %s", (NAME,)
).fetchone()
if __name__ == "__main__":
for fn in (orm, core, raw):
print(f"{fn.__name__:5} {fn()}")
PY
uv run lookup.pyThe three answers are the same, but what you hold differs. The ORM gives you a Rider object that the session tracks: change rider.city and call session.commit(), and SQLAlchemy writes the UPDATE for you. Core gives you a row, which is a named tuple. psycopg gives you a plain tuple, and the SQL is exactly the string you wrote.
All three send values as parameters, never pasted into the SQL text. With the ORM and Core that happens without you thinking about it. With raw SQL it is your job on every query: %s plus a tuple, never an f-string.
Now see what the ORM sends. Run the ORM function with echo on:
SQL_ECHO=1 uv run python -c "import lookup; lookup.orm()"The log shows something like this. Each line also starts with a timestamp, and the parameter style and timing text vary:
INFO sqlalchemy.engine.Engine BEGIN (implicit)
INFO sqlalchemy.engine.Engine SELECT riders.id, riders.name, riders.city
FROM riders
WHERE riders.name = %(name_1)s::VARCHAR
INFO sqlalchemy.engine.Engine [generated in 0.00015s] {'name_1': 'Rider 004'}
INFO sqlalchemy.engine.Engine ROLLBACKIt also shows a few queries SQLAlchemy runs once per process on its first connection, such as reading the server version.
Check it worked
uv run lookup.py printed three lines, and each ended in ('Rider 004', 'Lagos'). The echo log showed a SELECT on riders with the name sent as a separate parameter. The ORM selected every mapped column (id too) because it builds a whole object; Core and raw SQL fetched only the two columns you asked for.
Step 4 · Build a join and GROUP BY report three ways
The report: for each city, the number of delivered jobs in 2025 and the fees they earned. Write report.py:
cat > report.py <<'PY'
import os
from datetime import date
import psycopg
from sqlalchemy import func, select
from sqlalchemy.orm import Session
from models import Delivery, Rider, engine
START, END = date(2025, 1, 1), date(2026, 1, 1)
def orm():
stmt = (
select(Rider.city, func.count(Delivery.id), func.sum(Delivery.fee))
.join(Rider.deliveries)
.where(
Delivery.status == "delivered",
Delivery.delivered_on >= START,
Delivery.delivered_on < END,
)
.group_by(Rider.city)
.order_by(Rider.city)
)
with Session(engine) as session:
return [tuple(row) for row in session.execute(stmt)]
def core():
r, d = Rider.__table__, Delivery.__table__
stmt = (
select(r.c.city, func.count(d.c.id), func.sum(d.c.fee))
.select_from(r.join(d))
.where(d.c.status == "delivered", d.c.delivered_on >= START, d.c.delivered_on < END)
.group_by(r.c.city)
.order_by(r.c.city)
)
with engine.connect() as conn:
return [tuple(row) for row in conn.execute(stmt)]
def raw():
sql = """
SELECT r.city, count(d.id), sum(d.fee)
FROM riders AS r
JOIN deliveries AS d ON d.rider_id = r.id
WHERE d.status = 'delivered'
AND d.delivered_on >= %s AND d.delivered_on < %s
GROUP BY r.city
ORDER BY r.city
"""
with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
return conn.execute(sql, (START, END)).fetchall()
if __name__ == "__main__":
results = {fn.__name__: fn() for fn in (orm, core, raw)}
for city, jobs, fees in results["raw"]:
print(f"{city:8} {jobs:5} {fees}")
print("all three match:", results["orm"] == results["core"] == results["raw"])
PY
uv run report.pyLook at the ORM and Core versions side by side: they are nearly the same code. For reports, the ORM's select() is Core with class attributes in place of table columns, and you get rows back, not objects. The ORM adds one thing here: .join(Rider.deliveries) reads the join condition from the relationship, where Core's r.join(d) reads it from the foreign key.
The raw version is the one a database administrator or data analyst can paste straight into psql. The builder versions earn their keep when the query changes shape at run time. Adding an optional city filter from a search form is one line in Core (if city: stmt = stmt.where(r.c.city == city)); in raw SQL you end up joining strings, which is where mistakes and injection bugs creep in.
Check it worked
The output is:
Accra 5212 17934200.00
Kigali 4181 14331400.00
Lagos 5212 17831600.00
Nairobi 4181 14342800.00
all three match: TrueStep 5 · Cause the N+1 problem and fix it with selectinload
Lazy loading is the ORM default: rider.deliveries stays unloaded until your code touches it, and then SQLAlchemy runs a query for that one rider. In a loop over 50 riders, that is 1 query for the riders plus 50 more, one per rider. This is the N+1 problem, and it is the most common way an ORM app gets slow without anyone noticing, because each query on its own is fast.
Write nplus1.py, which counts every statement the engine sends:
cat > nplus1.py <<'PY'
import time
from sqlalchemy import event, select
from sqlalchemy.orm import Session, selectinload
from models import Rider, engine
# Connect once first, so SQLAlchemy's first-connection queries are not counted.
with engine.connect() as conn:
conn.exec_driver_sql("SELECT 1")
queries = 0
def count_query(*args):
global queries
queries += 1
event.listen(engine, "before_cursor_execute", count_query)
def jobs_per_rider(options=()):
global queries
queries = 0
start = time.perf_counter()
with Session(engine) as session:
riders = session.scalars(
select(Rider).where(Rider.city == "Lagos").options(*options)
).all()
totals = {rider.name: len(rider.deliveries) for rider in riders}
return len(totals), queries, time.perf_counter() - start
print("lazy loading: riders=%d queries=%d %.3fs" % jobs_per_rider())
print("selectinload: riders=%d queries=%d %.3fs" % jobs_per_rider([selectinload(Rider.deliveries)]))
PY
uv run nplus1.pyselectinload(Rider.deliveries) tells SQLAlchemy to load the relationship up front: after fetching the riders it runs one more query, ... WHERE deliveries.rider_id IN (...), with all 50 ids, and fills in every list. Run SQL_ECHO=1 uv run nplus1.py to see the 50 separate SELECT ... FROM deliveries statements in the first run and the single IN query in the second.
The timings depend on your machine. On one laptop with the database next to it, the difference is small. Every query is a round trip, though, so the gap grows with the distance between app and database: an app on a cloud server in one region talking to a database in another, or a developer on a mobile data connection reaching a hosted database, pays that delay 51 times instead of twice. On prepaid data the extra traffic also costs money.
Raw SQL and Core cannot have this bug in the same hidden way, because every query is one you wrote. You can still write a loop that queries once per rider, but you can see it in the code.
Check it worked
The first two fields of each line are fixed; the times are not:
lazy loading: riders=50 queries=51 0.061s
selectinload: riders=50 queries=2 0.032sStep 6 · Time a bulk update each way
The job: archive every delivered job from before 1 July 2025. That is 9,324 rows. There are two ways to do it with the ORM, so bulk.py times four functions. Each one rolls back at the end, so every run starts from the same data and the database is left unchanged:
cat > bulk.py <<'PY'
import os
import time
from datetime import date
import psycopg
from sqlalchemy import select, update
from sqlalchemy.orm import Session
from models import Delivery, engine
CUTOFF = date(2025, 7, 1)
def orm_objects():
# Load every row as an object, change it in Python, let the session write it back.
with Session(engine) as session:
rows = session.scalars(
select(Delivery).where(Delivery.status == "delivered", Delivery.delivered_on < CUTOFF)
).all()
for delivery in rows:
delivery.status = "archived"
session.flush()
session.rollback()
return len(rows)
def orm_statement():
# One UPDATE statement, built from the mapped class and run through the session.
with Session(engine) as session:
result = session.execute(
update(Delivery)
.where(Delivery.status == "delivered", Delivery.delivered_on < CUTOFF)
.values(status="archived")
)
session.rollback()
return result.rowcount
def core():
d = Delivery.__table__
with engine.connect() as conn:
result = conn.execute(
update(d)
.where(d.c.status == "delivered", d.c.delivered_on < CUTOFF)
.values(status="archived")
)
conn.rollback()
return result.rowcount
def raw():
with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
cur = conn.execute(
"UPDATE deliveries SET status = 'archived'"
" WHERE status = 'delivered' AND delivered_on < %s",
(CUTOFF,),
)
conn.rollback()
return cur.rowcount
if __name__ == "__main__":
for fn in (orm_objects, orm_statement, core, raw):
start = time.perf_counter()
rows = fn()
print(f"{fn.__name__:14} rows={rows} {time.perf_counter() - start:.3f}s")
PY
uv run bulk.pyorm_objects is the version people write first, because it reads like ordinary Python. It moves all 9,324 rows from the database into Python, builds an object for each one, tracks the change, and sends the changed rows back as a batch of UPDATE ... WHERE id = ... statements. The other three send one UPDATE and let PostgreSQL do the work where the data lives, so they finish in a fraction of the time and close to each other.
The fix is not to leave the ORM. orm_statement is still ORM code: update(Delivery) uses the mapped class, runs in the session, and by default updates any matching objects the session already holds so they do not go stale. Reach for object-by-object changes when each row needs its own Python logic; use a statement when one rule applies to every row.
Check it worked
Four lines print, each with rows=9324. orm_objects has the largest time, often many times the others:
orm_objects rows=9324 0.912s
orm_statement rows=9324 0.041s
core rows=9324 0.036s
raw rows=9324 0.030sBecause every function rolled back, nothing was archived:
psql "$DATABASE_URL" -X -Atc "SELECT count(*) FROM deliveries WHERE status = 'archived';"It prints 0.
Step 7 · Mix the layers and choose per query
You do not have to choose once for the whole project. SQLAlchemy runs your own SQL through the same session with text(), so an ORM app can keep one hand-written query where SQL says it best. This one finds the top-earning rider in each city with a window function, which is awkward to express through a builder and clear as SQL. The :status placeholder is a bound parameter, sent separately like %s in psycopg:
cat > mix.py <<'PY'
from sqlalchemy import text
from sqlalchemy.orm import Session
from models import engine
TOP_RIDERS = text("""
SELECT city, name, total
FROM (
SELECT r.city, r.name, sum(d.fee) AS total,
rank() OVER (PARTITION BY r.city ORDER BY sum(d.fee) DESC, r.name) AS place
FROM riders AS r
JOIN deliveries AS d ON d.rider_id = r.id
WHERE d.status = :status
GROUP BY r.city, r.name
) AS ranked
WHERE place = 1
ORDER BY city
""")
with Session(engine) as session:
for city, name, total in session.execute(TOP_RIDERS, {"status": "delivered"}):
print(f"{city:8} {name} {total}")
PY
uv run mix.pyUse what you saw in this tutorial to choose for each query in your own project:
- Raw SQL through the driver suits scripts, data loads (psycopg's
COPY), and reports that people who think in SQL will maintain or paste intopsql. It also suits PostgreSQL features a builder does not cover well. You pay by mapping rows to Python yourself, by keeping every value in a parameter, and by finding queries with a text search when a column is renamed. - A query builder (Core) suits queries whose shape changes at run time: optional filters, user-chosen sort columns, pagination. You stay close to the SQL and get rows back, and the builder keeps parameters safe while you compose. There is no tracking of objects, so writes are statements you write.
- The ORM suits an app with many related tables where most work is reading, editing and saving a few records at a time. The session tracks changes and writes them in one transaction. You pay in queries you did not write: check them with
echo, pick loader options such asselectinloadfor anything you loop over, and useupdate()anddelete()statements for bulk work. - Mixing them is normal. A common split is the ORM for everyday reads and writes, Core for the search page,
text()for the two or three hard reports, and the driver'sCOPYfor imports.
Three questions settle most cases: who will read and change this query, does its shape change at run time, and how many rows does one call touch? Write the answers for your hardest query next to it as a comment.
Check it worked
mix.py prints four lines, one per city in alphabetical order, each with the name of a rider and a total that is the largest in that city, starting with an Accra line.
Step 8 · Clean up
This deletes the demo project, the courier database with every row in it, and the courierapp role. Leave the project folder first:
cd ~
rm -rf ~/orm-demo
sudo -u postgres dropdb courier
sudo -u postgres dropuser courierapp
unset DATABASE_URLOpen ~/.pgpass in your editor and delete the localhost:5432:courier:courierapp:... line. If it was the only line, delete the file with rm ~/.pgpass.
Check it worked
sudo -u postgres psql -X -Atc "SELECT count(*) FROM pg_database WHERE datname = 'courier';" -c "SELECT count(*) FROM pg_roles WHERE rolname = 'courierapp';"Both lines print 0.
Next steps
- Find out why a query the ORM generated is slow, by reading its plan: /tutorials/speed-up-slow-postgres-queries-with-explain.
- Use the ORM inside a web API, with SQLModel on top of SQLAlchemy: /tutorials/connect-fastapi-to-a-database-with-sqlmodel.
- Go deeper on the driver layer, including
COPY, pools and error codes: /tutorials/connect-to-postgresql-from-python-with-psycopg.
Related tutorials
- Connect to PostgreSQL from Python with psycopg 3You will connect a Python 3.15 project to PostgreSQL 18 with psycopg 3.3, run parameterised queries, shape rows as dicts and dataclasses, group writes in transactions, load 100,000 rows with COPY, stream large results, share connections with a pool and handle errors by SQLSTATE.
- How to Find and Fix Slow PostgreSQL Queries with EXPLAIN ANALYZEYou will read a PostgreSQL 18 query plan, add an index that turns a 40 ms table scan into a 0.2 ms lookup, and use pg_stat_statements to find which queries deserve that effort.
- Connect FastAPI to a database with SQLModelYou will move a FastAPI items API from memory into a database with SQLModel, with separate models for input and output, a session per request, tables created at startup, paginated lists and data that survives a restart.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials