What is an ORM or query builder? Compare Prisma, Sequelize, TypeORM, and the raw driver.
3 minintermediatenodejsormprismasequelizequery-builder
Quick Answer
An ORM maps database rows to JavaScript objects and generates SQL for you; a query builder gives a programmatic API to compose SQL without full object mapping. They trade some control and performance for productivity, type safety, and migrations. The raw driver gives maximum control but the most boilerplate.
Detailed Answer
Answer:
The spectrum, from most control to most abstraction:
- Raw driver (
pg,mysql2,mongodb) — you write SQL/queries yourself. - Query builder (
Knex) — compose SQL with a fluent JS API. - ORM (Prisma, Sequelize, TypeORM, Mongoose) — map tables/collections to objects/models, generate queries, manage migrations.
Raw driver:
const { rows } = await pool.query('SELECT * FROM users WHERE id = $1', [id]);
Max control and performance, but lots of boilerplate and manual mapping.
ORMs compared:
| Tool | Style | Notes |
|---|---|---|
| Prisma | schema-first, generated client | Excellent TypeScript types, great DX, explicit migrations; less flexible for very complex/raw SQL (has $queryRaw escape hatch). |
| Sequelize | mature, model-based | Widely used, lots of features; typing historically weaker. |
| TypeORM | decorator/entity based | Active Record or Data Mapper; TS-native; some rough edges. |
| Mongoose | ODM for MongoDB | Schemas/validation on top of a schemaless DB. |
Trade-offs:
- Pros: productivity, migrations, validation, type safety (Prisma especially), protection from injection via parameterization.
- Cons: abstraction can generate inefficient SQL, hide the N+1 problem, and make complex queries awkward — you sometimes drop to raw SQL anyway.
Guidance: Prisma is a strong default for new TypeScript apps (types + DX). Use a query builder (Knex) when you want SQL control with less magic, and the raw driver for hot paths or very complex queries. Whatever you pick, understand the SQL it generates.