Database Programming Features · Lesson 86 of 112

Database ORMs and Access Layers

What you will learn

  • What an ORM is and why it exists
  • Where an ORM helps and where it hurts
  • The N+1 query problem, with real numbers
  • The alternatives: raw SQL, query builders and a repository layer
  • How to choose without dogma

1. The mismatch

Your program thinks in objects: a Book with an author. The database thinks in tables and rows with foreign keys (chapter 3). Turning one into the other by hand is repetitive code: build the INSERT, read rows, copy columns into attributes.

An ORM (object-relational mapper) automates that. You describe a class, the ORM maps it to a table, and it writes SQL for you when you work with objects. Many web frameworks include one. The Django framework behind many Python sites, for example, has its own ORM. We use plain sqlite3 here so every query is visible.

2. What an ORM gives you

  • Less repetitive code for common create, read, update and delete jobs.
  • Safer queries. Mapped parameters help avoid SQL injection (lesson 8.5).
  • Portability between database products, within limits.
  • Migrations support in many tools (lesson 8.7).

3. What it can cost you

  • Hidden SQL. You may not know which queries run, and a nice-looking line of code can fire many of them.
  • Hard cases. Complex reports, window functions and special features are awkward, so you still need SQL.
  • A leaky abstraction. Performance and locking still depend on the real database (chapters 6 and 7).

4. The N+1 problem

The classic ORM trap is easiest to see without an ORM. We load five books, then print each book's author. A mapped object can fetch its author lazily, only when you ask for it:

import sqlite3
con = sqlite3.connect(":memory:")
con.executescript("""
CREATE TABLE authors (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT, author_id INTEGER REFERENCES authors(id));
INSERT INTO authors (name) VALUES ('Rina'), ('Sam'), ('Lee');
INSERT INTO books (title, author_id) VALUES ('B1',1),('B2',1),('B3',2),('B4',3),('B5',3);
""")
queries = 0

class Book:
    def __init__(self, id, title, author_id):
        self.id, self.title, self.author_id = id, title, author_id
    @property
    def author(self):
        global queries
        queries += 1
        return con.execute("SELECT name FROM authors WHERE id = ?", (self.author_id,)).fetchone()[0]

queries = 1                      # the first query below
books = [Book(*r) for r in con.execute("SELECT id, title, author_id FROM books")]
print([(b.title, b.author) for b in books])
print("queries run (N+1):", queries)
[('B1', 'Rina'), ('B2', 'Rina'), ('B3', 'Sam'), ('B4', 'Lee'), ('B5', 'Lee')]
queries run (N+1): 6

One query loaded the five books, and one more query per book loaded each author: 1 + 5 = 6 queries. With 5,000 books it would be 5,001. That is the N+1 problem. Over a network (lesson 1.5) each query costs a round trip, so it hurts quickly.

The fix is to ask for related rows together, with a join:

rows = con.execute("SELECT b.title, a.name FROM books b JOIN authors a ON a.id = b.author_id").fetchall()
print(rows)
print("queries run with a join: 1")
[('B1', 'Rina'), ('B2', 'Rina'), ('B3', 'Sam'), ('B4', 'Lee'), ('B5', 'Lee')]
queries run with a join: 1

The same idea on the sample data. This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). Instead of asking for 5 rows and then 5 separate parents, one join returns each row together with its parent:

SELECT p.name AS product, c.name AS category
FROM products p JOIN categories c ON c.category_id = p.category_id
ORDER BY p.product_id LIMIT 5;
product           category
----------------  --------
Steel pan         Kitchen
Ceramic mug       Kitchen
Wooden spoon set  Kitchen
Glass jar         Kitchen
Chopping board    Kitchen
(5 rows)
SELECT a.account_id, a.account_type, b.name AS branch
FROM accounts a JOIN branches b ON b.branch_id = a.branch_id
ORDER BY a.account_id LIMIT 5;
account_id  account_type  branch
----------  ------------  ---------
         1  checking      Central
         2  savings       Riverside
         3  savings       Airport
         4  checking      Central
         5  checking      Airport
(5 rows)
SELECT s.section_id, c.title AS course, t.name AS teacher
FROM sections s JOIN courses c ON c.course_id = s.course_id JOIN teachers t ON t.teacher_id = s.teacher_id
ORDER BY s.section_id LIMIT 5;
section_id  course                  teacher
----------  ----------------------  -------------
         1  Foundations of Algebra  Liam Patel
         2  Geometry                Bruno Bianchi
         3  Geometry                Sven Silva
         4  Geometry                Kira Perez
         5  Statistics              Nico Diaz
(5 rows)

Five rows, each with its parent, in one query. A lazy loop would have run one more query per row.

The same answer arrives with one query. Most ORMs have a way to ask for this, usually called "eager loading" or "prefetching" (Django, for example, has select_related for this case; this is from general knowledge and is not run here). The skill is to notice when it is needed, by logging the SQL the ORM runs.

Quick check: how many queries does N+1 run for 200 books?

201: one to load the books and 200 to load their authors.

5. Other ways to talk to the database

Style What it is Good for
Raw SQL you write the SQL and read rows yourself full control, complex queries, small programs
Query builder you build SQL with code (table.select().where(...)) dynamic filters without string gluing
ORM classes map to tables typical create/read/update/delete apps
Repository layer your own module is the only place that touches the database keeping SQL out of the rest of the program, whichever tool is used inside

Whatever you choose, two habits stay the same: always pass values as parameters (never glue user text into SQL), and look at the SQL that actually runs.

Worked example: a team's decision

A team builds an online shop with a web framework.

  • Day-to-day pages (list products, add to basket, edit profile): use the framework's ORM, with eager loading wherever a page shows related rows.
  • The monthly sales report with grouping and window functions: write raw SQL in a reports module and test it against known numbers.
  • Turn on query logging in development, and set a rule: a page may not run more than a small, agreed number of queries.

The result mixes tools by need rather than choosing one forever. The team is made up.

Common mistakes

  • Never looking at the generated SQL and missing N+1 queries.
  • Loading whole objects when you only need one column.
  • Using the ORM for heavy reporting and fighting it, when raw SQL would be clearer.
  • Believing an ORM makes the database choice irrelevant. Differences still show up.
  • Gluing user text into a raw SQL string instead of using parameters.

Key takeaways

  • An ORM maps classes to tables and writes routine SQL for you.
  • It saves repetitive code but hides the SQL, and still needs raw SQL for hard cases.
  • N+1 means one query for a list plus one per row; the fix is loading related rows together (a join or eager loading).
  • Raw SQL, query builders, ORMs and repository layers can be mixed.
  • Always use parameters and watch the SQL that really runs.

Practice

1. What problem does an ORM solve?

Show answer

It translates between objects in the program and rows in tables, so you do not hand-write the routine SQL and copying code.

2. In the lesson, why were 6 queries run for 5 books?

Show answer

One query loaded the books, then each of the five books made its own query to load its author: 1 + 5.

3. How was the N+1 problem fixed in the example?

Show answer

By joining books to authors in one query, so all the data arrived together.

4. Give one advantage and one disadvantage of an ORM.

Show answer

Advantage (any): less repetitive code, safer parameter handling, some portability. Disadvantage (any): hidden SQL, awkward for complex queries, performance surprises such as N+1.

5. How can you find out that a page is running too many queries?

Show answer

Turn on query logging (or a query counter) in development and look at what SQL actually runs for that page.

6. When would you choose raw SQL over an ORM?

Show answer

For complex reports and queries (grouping, window functions, special features) that are awkward or slow to express through the ORM, or when you need full control of the SQL.