ORM
Object-Relational Mapping. A technique that converts data between incompatible type systems in object-oriented languages and relational databases.
Detailed Explanation
ORMs let you interact with databases using your programming language's syntax instead of writing SQL. Instead of `SELECT * FROM users WHERE id = 1`, you write `User.findById(1)`. The ORM translates this to SQL and maps the results to language objects.
Popular ORMs: Prisma (TypeScript/JavaScript, type-safe, modern), SQLAlchemy (Python, mature, flexible), Sequelize (JavaScript, legacy), TypeORM (TypeScript, Active Record pattern), and Drizzle (TypeScript, SQL-like). ORMs handle migrations, relationships, validation, and query building—but can generate inefficient queries for complex operations.
Why It Matters
ORMs speed up development, reduce SQL errors, and provide type safety. However, knowing when to drop down to raw SQL is essential for performance.
Real-World Example
A developer uses Prisma to define a User model. Prisma generates TypeScript types, migration SQL, and a query client. The developer writes `prisma.user.create({ data: { name: "Alice", email: "alice@example.com" } })` instead of raw SQL.
When to Use
For most database interactions in application code. Use raw SQL for complex queries, performance optimization, and database-specific features that ORMs don't support.
Advantages
- Faster development with language-native syntax
- Type safety and autocompletion
- Automatic migration generation
- Relationship handling is simplified
- Database-agnostic code (switch databases easily)
Disadvantages
- Generated SQL can be inefficient
- N+1 query problems are common
- Learning curve for ORM-specific syntax
- Complex queries are harder than raw SQL
- Overhead for simple operations
Frequently Asked Questions
Should I use an ORM or raw SQL?
Use an ORM for most operations (CRUD, simple joins, migrations). Use raw SQL for complex queries, performance optimization, and database-specific features. Many ORMs support raw SQL for when you need it.
What is the best ORM for Node.js?
Prisma is the modern choice (type-safe, great DX, migrations). Drizzle is lighter and SQL-like. TypeORM follows the Active Record pattern. Sequelize is legacy but widely used. Start with Prisma for new projects.
What is N+1 problem in ORMs?
The N+1 problem occurs when an ORM makes 1 query for a list of items and N additional queries for each item's related data. Use eager loading (include/join) to fetch related data in a single query.
Do ORMs support database migrations?
Yes. Most ORMs (Prisma, Sequelize, TypeORM) can generate and run migrations based on schema changes. This is one of the biggest advantages of using an ORM—schema version control is built in.
Can I use an ORM with an existing database?
Yes. Most ORMs can introspect existing databases and generate models. Prisma: `prisma db pull`. SQLAlchemy: reflection. This lets you adopt an ORM incrementally on existing projects.