# ORM

> The ORM (Object-Relational Mapping) is a technique that lets developers interact with a database using object-oriented code instead of raw SQL queries.

## What is an ORM and should I use one?

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.

- Topic: Databases
- Type: concept, tool

## Example

Wrong:

```ts
const users = await db.user.findMany();
for (const user of users) {
  user.posts = await db.post.findMany({ where: { authorId: user.id } });
}
```

Right:

```ts
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.

## Related cards

- [SQL](https://wonderium.dev/engineering/sql.md)
- [Relational Database](https://wonderium.dev/engineering/relational-db.md)
- [Databases](https://wonderium.dev/engineering/databases.md)
- [Abstraction](https://wonderium.dev/engineering/abstraction.md)
- [SQL Injection](https://wonderium.dev/web/sql-injection.md)

---

- Level: [Engineering](https://wonderium.dev/engineering.md)
- HTML version: https://wonderium.dev/engineering/orm
- Last updated: 2026-11-25
