ORM

Term side of the Card.
Topic: Databases
Unit title: ORM
Categories: Concept, Tool
Explanation side of the Card

Explanation: The technique that enables mapping of objects in object-oriented programming languages to relational database tables. It simplifies database operations by enabling developers to manipulate data as objects, reducing the need for SQL queries.

Example

Wrongts
const users = await db.user.findMany();
for (const user of users) {
  user.posts = await db.post.findMany({ where: { authorId: user.id } });
}
Rightts
const users = await db.user.findMany({
  include: { posts: true },
});

Loading the relation with the users avoids the N+1 problem of one extra query per user.

Common mistakes

  • Querying inside a loop, causing the N+1 problem with hundreds of small queries.
  • Loading whole tables into memory and filtering in code instead of in the query.

Key points

  • Related records are loaded with eager loading or a join, not a query inside a loop.
  • Raw SQL through the ORM uses parameter binding, not string interpolation.
  • Schema changes go through migrations, not automatic schema sync in production.

Interview questions

Do ORMs prevent SQL injection?

Queries the ORM builds are parameterized, so they are safe. Raw queries built with string interpolation are still vulnerable.

ORM vs query builder: what's the difference?

A query builder helps you write SQL in code but returns plain rows. An ORM also maps rows to objects and manages relations.

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy