ORMs and Query Builders

Use an ORM or query builder productively while staying aware of the SQL it generates.

Intermediate · about 8 hours · difficulty 3/5

Learn first: Writing SQL Queries

An ORM (Object-Relational Mapper) maps tables to classes or objects so you can write user.orders instead of SQL. A query builder is lighter: it builds SQL with code but keeps you close to the query. Both save time and reduce injection risk; both can hide expensive queries.

Common choices

  • Node/TypeScript: Prisma, Drizzle, TypeORM, Knex (query builder), Kysely.
  • Python: SQLAlchemy, Django ORM.
  • Java: Hibernate / JPA. C#: Entity Framework Core. Ruby: ActiveRecord. Go: sqlc, GORM.

The N+1 problem

The classic ORM trap: load 50 posts (1 query), then access post.author in a loop, which triggers 50 more queries. The fix is eager loading (include, joinedload, includes) or a join. Always enable query logging in development so you see this happen.

Good habits

  • Log SQL in development and read it.
  • Select only the fields you need.
  • Drop to raw SQL for complex reports; every good ORM allows it with parameters.
  • Keep the ORM in a data access layer so business logic does not depend on its quirks.

Pitfalls

  • Treating the ORM as a way to never learn SQL. You will eventually need to debug what it emits.

You are ready to move on when you can spot and fix an N+1 query by reading the query log, and write the same query in both your ORM and raw SQL.

Key concepts

  • Active Record vs Data Mapper
  • Prisma or Drizzle (Node)
  • SQLAlchemy, Hibernate, EF Core
  • Query builders (Knex, Kysely)
  • N+1 queries and eager loading
  • Query logging
  • Raw SQL escape hatches

Mini project

Build an endpoint that lists 50 posts with authors and comment counts. First write it naively and count the queries in the log, then fix it to use at most 2 queries.

Check yourself

How would you detect an N+1 query problem in an app you did not write?

Free resources