ORMs and Query Builders

Updated · 13 min read
mediumPostgreSQL 18sqlormhibernatesqlalchemyprisman-plus-oneperformanceinterview

An ORM (object-relational mapper) lets a program work with database rows as objects in its own language, and writes the SQL for you. Instead of SELECT first_name FROM students WHERE student_id = 101, you write something like session.get(Student, 101).first_name. A query builder is a lighter tool: you build SQL with method calls, such as db.select('first_name').from('students').where('student_id', 101), and it returns plain rows. Both save a lot of repetitive code, but both still send SQL to the database, and you are still responsible for that SQL. In this lesson, we will see what an ORM does, run into the most common ORM performance bug, the N+1 query problem, watch the exact SQL a real ORM sends, fix it two ways, and decide when to write SQL yourself. The ORM examples use SQLAlchemy 2.0 in Python against the Fee Tracker; the output shown is what it printed.

In One Minute

  • An ORM maps tables to classes and rows to objects, and generates SQL for you.
  • A query builder builds SQL with method calls and returns rows; it maps less and hides less.
  • N+1: loading a list (1 query), then a related list for each item (N more queries). Ten thousand customers become ten thousand and one queries.
  • Fix N+1 by loading related rows up front (eager loading), or by writing one query with a join.
  • Always look at the SQL an ORM sends: turn on its SQL logging in development.
  • Use the ORM for everyday reads and writes; write SQL yourself for reports, bulk changes and anything performance-critical.

What an ORM Does

An ORM connects two worlds: classes and objects in your code, and tables and rows in the database.

DatabaseORM
Table studentsClass Student
RowAn object (instance)
Column first_nameField or attribute first_name
Foreign key payments.student_idA relationship: student.payments, payment.student
INSERT, UPDATE, DELETEsave(), changing a field, delete(), then a commit or flush

Every popular language has them:

LanguageORMsQuery builders
JavaJPA with Hibernate (the most widely used), Spring Data JPAjOOQ, Spring's JdbcTemplate (plain SQL helper)
JavaScript / TypeScriptPrisma, TypeORM, Sequelize, MikroORMKnex, Kysely, Drizzle (both a builder and a light ORM)
PythonSQLAlchemy ORM, Django ORMSQLAlchemy Core

Here are the Fee Tracker's students and payments as SQLAlchemy classes. A Hibernate @Entity class or a Prisma model block describes the same thing:

Python
import os
from datetime import date
from decimal import Decimal
 
from sqlalchemy import ForeignKey, create_engine, event
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
 
URL = "postgresql+psycopg://fee_app@localhost:5432/feetracker"
engine = create_engine(
    URL, connect_args={"password": os.environ["FEE_DB_PASSWORD"]})
 
class Base(DeclarativeBase):
    pass
 
class Student(Base):
    __tablename__ = "students"
    student_id: Mapped[int] = mapped_column(primary_key=True)
    first_name: Mapped[str]
    payments: Mapped[list["Payment"]] = relationship(back_populates="student")
 
class Payment(Base):
    __tablename__ = "payments"
    payment_id: Mapped[int] = mapped_column(primary_key=True)
    student_id: Mapped[int] = mapped_column(ForeignKey("students.student_id"))
    amount_usd: Mapped[Decimal]
    paid_on: Mapped[date]
    student: Mapped[Student] = relationship(back_populates="payments")
 
# Print every SQL statement the ORM sends, numbered.
sent = []
 
@event.listens_for(engine, "before_cursor_execute")
def show_sql(conn, cursor, statement, parameters, context, executemany):
    sent.append(statement)
    print(f"-- SQL {len(sent)}: " + " ".join(statement.split()))

Explanation: Each class names its table with __tablename__, and each Mapped[...] attribute is a column. relationship(...) gives every Student a payments list and every Payment a student, joined through the foreign key. The last part isn't needed for a real app: it prints every SQL statement the ORM sends, numbered, so we can see exactly what happens. (Hibernate's show_sql setting, Prisma's log: ['query'] option and Django's connection.queries do the same job.)

Table to class, column to attribute, foreign key to relationship

The N+1 Query Problem

The N+1 problem happens when code loads a list of N items with one query, then touches a related list for each item, and the ORM quietly runs one more query per item. Here we list each student with their number of payments and total paid:

Python
from sqlalchemy import select
from sqlalchemy.orm import Session
 
from models import Student, engine, sent
 
with Session(engine) as session:
    students = session.scalars(
        select(Student).order_by(Student.student_id)).all()
    for s in students:
        total = sum(p.amount_usd for p in s.payments)   # lazy load!
        print(f"{s.first_name}: {len(s.payments)} payments, ${total}")
 
print("SQL statements sent:", len(sent))
Output
-- SQL 1: SELECT students.student_id, students.first_name FROM students ORDER BY students.student_id
-- SQL 2: SELECT payments.payment_id AS payments_payment_id, payments.student_id AS payments_student_id, payments.amount_usd AS payments_amount_usd, payments.paid_on AS payments_paid_on FROM payments WHERE %(param_1)s::INTEGER = payments.student_id
Srihitha: 5 payments, $1700.00
-- SQL 3: SELECT payments.payment_id AS payments_payment_id, payments.student_id AS payments_student_id, payments.amount_usd AS payments_amount_usd, payments.paid_on AS payments_paid_on FROM payments WHERE %(param_1)s::INTEGER = payments.student_id
Advitha: 0 payments, $0
-- SQL 4: SELECT payments.payment_id AS payments_payment_id, payments.student_id AS payments_student_id, payments.amount_usd AS payments_amount_usd, payments.paid_on AS payments_paid_on FROM payments WHERE %(param_1)s::INTEGER = payments.student_id
Navika: 2 payments, $450.00
SQL statements sent: 4

Explanation: SQL 1 loads the three students. The code looks innocent, but s.payments is lazy: the ORM doesn't load a student's payments until the code first touches them. So the loop sends SQL 2, 3 and 4, one per student, each running WHERE ... = payments.student_id with that student's id as the parameter. Three students cost four queries: 1 for the list, plus N = 3 for the payments. With 10,000 students it would be 10,001 queries, each one a round trip to the database, and the page that worked fine in testing becomes slow in production.

Here is exactly what the database receives, written as plain SQL you can run:

SQL▶ Try it
-- 1 query for the list
SELECT student_id, first_name FROM students ORDER BY student_id;
 
-- then N queries, one per student
SELECT payment_id, amount_usd FROM payments WHERE student_id = 101
  ORDER BY payment_id;
SELECT payment_id, amount_usd FROM payments WHERE student_id = 102
  ORDER BY payment_id;
SELECT payment_id, amount_usd FROM payments WHERE student_id = 103
  ORDER BY payment_id;
Output
 student_id | first_name
------------+------------
        101 | Srihitha
        102 | Advitha
        103 | Navika
(3 rows)
 
 payment_id | amount_usd
------------+------------
          1 |     450.00
          2 |     250.00
          3 |     250.00
          4 |     550.00
          5 |     200.00
(5 rows)
 
 payment_id | amount_usd
------------+------------
(0 rows)
 
 payment_id | amount_usd
------------+------------
          6 |     225.00
          7 |     225.00
(2 rows)

Explanation: Each query is fast on its own; the problem is how many there are. Each one costs a network round trip, often a millisecond or more, and work for the database to parse and plan.

Lazy loading sends one extra query per item: 1 + N

Fixing N+1

Fix 1: eager loading. Tell the ORM, in the query, that you'll need the related rows, so it loads them all at once:

Python
from sqlalchemy import select
from sqlalchemy.orm import Session, selectinload
 
from models import Student, engine, sent
 
with Session(engine) as session:
    students = session.scalars(
        select(Student)
        .options(selectinload(Student.payments))    # load them up front
        .order_by(Student.student_id)).all()
    for s in students:
        total = sum(p.amount_usd for p in s.payments)
        print(f"{s.first_name}: {len(s.payments)} payments, ${total}")
 
print("SQL statements sent:", len(sent))
Output
-- SQL 1: SELECT students.student_id, students.first_name FROM students ORDER BY students.student_id
-- SQL 2: SELECT payments.student_id AS payments_student_id, payments.payment_id AS payments_payment_id, payments.amount_usd AS payments_amount_usd, payments.paid_on AS payments_paid_on FROM payments WHERE payments.student_id IN (%(primary_keys_1)s::INTEGER, %(primary_keys_2)s::INTEGER, %(primary_keys_3)s::INTEGER)
Srihitha: 5 payments, $1700.00
Advitha: 0 payments, $0
Navika: 2 payments, $450.00
SQL statements sent: 2

Explanation: selectinload(Student.payments) makes the ORM load every listed student's payments in one extra query, WHERE payments.student_id IN (...) with all three ids. Two queries now, whether there are 3 students or 10,000. Every ORM has a version: JOIN FETCH or an entity graph in JPA and Hibernate, include in Prisma, select_related and prefetch_related in Django, and joinedload in SQLAlchemy, which uses a single LEFT JOIN instead.

Fix 2: ask the database for the answer. This page only needs a count and a total per student. That is a GROUP BY question, and the database can answer it in one query without sending any payment rows at all:

Python
from sqlalchemy import text
from sqlalchemy.orm import Session
 
from models import engine, sent
 
REPORT = text("""
    SELECT s.first_name, count(p.payment_id) AS payments,
           coalesce(sum(p.amount_usd), 0) AS total
    FROM students s
    LEFT JOIN payments p ON p.student_id = s.student_id
    GROUP BY s.student_id, s.first_name
    ORDER BY s.student_id
""")
 
with Session(engine) as session:
    for name, count, total in session.execute(REPORT):
        print(f"{name}: {count} payments, ${total}")
 
print("SQL statements sent:", len(sent))
Output
-- SQL 1: SELECT s.first_name, count(p.payment_id) AS payments, coalesce(sum(p.amount_usd), 0) AS total FROM students s LEFT JOIN payments p ON p.student_id = s.student_id GROUP BY s.student_id, s.first_name ORDER BY s.student_id
Srihitha: 5 payments, $1700.00
Advitha: 0 payments, $0
Navika: 2 payments, $450.00
SQL statements sent: 1

Explanation: One query, and only three small rows come back. The LEFT JOIN keeps Advitha, who has no payments (LEFT JOIN), count(p.payment_id) counts only real payments, and coalesce(..., 0) turns her NULL sum into 0 (NULL Functions). text() runs plain SQL through the ORM's own connection, so it shares its transactions. Here is the same query in Try it:

SQL▶ Try it
SELECT s.first_name,
       count(p.payment_id)            AS payments,
       coalesce(sum(p.amount_usd), 0) AS total_usd
FROM students s
LEFT JOIN payments p ON p.student_id = s.student_id
GROUP BY s.student_id, s.first_name
ORDER BY s.student_id;
Output
 first_name | payments | total_usd
------------+----------+-----------
 Srihitha   |        5 |   1700.00
 Advitha    |        0 |         0
 Navika     |        2 |    450.00
(3 rows)
Real statement counts: lazy 4, eager 2, one GROUP BY query 1

Reading the SQL an ORM Sends

An ORM is only as fast as the SQL it generates, so read that SQL for every important page. Turn on statement logging (echo=True in SQLAlchemy, spring.jpa.show-sql=true in Spring, log: ['query'] in Prisma), then check three things:

Look forProblemFix
The same statement repeated with different idsN+1Eager loading, or one query with a join
SELECT of every column for a list that shows twoMoves data nobody usesSelect only the columns you need
No LIMIT on a list pageLoads every row into memoryPaginate (Pagination)
A query that filters on a column with no indexFull table scansAdd an index (Indexes); check with EXPLAIN

Copy a slow generated statement into psql and run it with EXPLAIN (ANALYZE) (Reading EXPLAIN). The database doesn't know or care that an ORM wrote it.

When to Write SQL Yourself

ORMs are excellent at the everyday work of loading one object, saving a form and following a relationship. They are weaker where SQL is strongest:

Use the ORM forWrite SQL for
Loading and saving single recordsReports with GROUP BY, window functions or CTEs (Window Functions)
Simple lists with filters and pagingUpdating or deleting thousands of rows at once
Following relationships, with eager loadingUpserts (Upsert and MERGE) and bulk loads
Keeping simple code readableQueries you've tuned with EXPLAIN

Every ORM lets you send plain SQL: text() in SQLAlchemy, native queries in JPA, $queryRaw in Prisma and raw() in Django. Always pass values as parameters there too; raw SQL inside an ORM can be injected just like any other SQL (SQL Injection).

Common Mistakes

Never looking at the generated SQL. N+1 and missing indexes stay hidden until production traffic arrives. Log SQL in development.

Touching relationships inside loops. Each touch can be a query. Load what the loop needs up front.

Loading whole tables into objects. Thousands of objects use memory and time. Filter, paginate, or let SQL aggregate.

Updating rows one object at a time. Changing 10,000 objects and saving each one is 10,000 UPDATE statements. Use one UPDATE ... WHERE instead.

Building raw SQL with string formatting. Parameters apply inside ORMs too.

Letting the ORM create the production schema. Automatic schema updates can drop or change columns; use migrations (Schema Migrations).

Interview Corner

What is the N+1 query problem?

Loading a list with one query and then running one more query per item to load related data, usually through lazy loading in an ORM. N items cost N+1 queries.

How do you fix N+1?

Load the related data up front with eager loading (JOIN FETCH in JPA, include in Prisma, selectinload/joinedload in SQLAlchemy, select_related/prefetch_related in Django), or replace the loop with one SQL query that joins or aggregates.

What is the difference between an ORM and a query builder?

An ORM maps rows to objects and tracks changes to save them; a query builder only helps you write SQL with code and returns plain rows. Query builders hide less of the SQL.

When would you bypass the ORM?

For reports and aggregations, bulk updates and deletes, upserts, and queries tuned with EXPLAIN, where SQL is clearer and faster, always using parameters.

Practice

Challenge: A page lists each course with how many students are enrolled. Written with lazy loading over courses and their enrollments, it sends 1 + 6 queries. Write the single SQL query the page should use instead, keeping courses with no enrollments, ordered by course_id.

Show solution
SQL▶ Try it
SELECT c.course_id, c.title,
       count(e.student_id) AS enrolled
FROM courses c
LEFT JOIN enrollments e ON e.course_id = c.course_id
GROUP BY c.course_id, c.title
ORDER BY c.course_id;
Output
 course_id |       title       | enrolled
-----------+-------------------+----------
         1 | Java Basics       |        2
         2 | Java OOP          |        1
         3 | Java Collections  |        1
         4 | SQL Basics        |        2
         5 | JavaScript Basics |        1
         6 | Git Basics        |        0
(6 rows)

One query returns six rows, one per course, instead of seven round trips. The LEFT JOIN keeps Git Basics, which has no enrollments, and count(e.student_id) counts it as 0, because count of a column skips NULLs.

Quick check: ORMs

4 questions
1A loop over 50 orders touches order.customer, which is lazy-loaded. How many queries run?
2What does eager loading do?
3What's the best first step when an ORM page is slow?
4Which task suits plain SQL better than ORM objects?

Key Takeaways

You want toIn SQLAlchemyIn JPA/HibernateIn Prisma
See the SQLcreate_engine(..., echo=True)spring.jpa.show-sql=truenew PrismaClient({ log: ['query'] })
Load related rows up frontselectinload(Student.payments)JOIN FETCH s.paymentsinclude: { payments: true }
Run plain SQLsession.execute(text(...), params)createNativeQuery(...)prisma.$queryRaw`...`

Was this tutorial helpful?

Lesson 105 of 115