Lesson 1 / 35

What an ORM Actually Does

Describe what an ORM maps, what work it saves, and why every ORM call still ends up as SQL sent to the database.

By · 15 years in web development

Objects on one side, tables on the other

An Object-Relational Mapper (ORM) is a library that translates between the objects in your program and the rows in a relational database. Your Node.js code works with a User object that has a name and a list of posts; the database stores a users table and a posts table linked by a foreign key. The ORM does three jobs: it maps classes or models to tables and fields to columns, it builds SQL from method calls such as findMany or save, and it hydrates the returned rows back into objects. The common misconception is that an ORM replaces SQL. It does not. Every call still becomes a SELECT, INSERT, UPDATE or DELETE that the database executes. The ORM only writes that SQL for you, so you still need to understand what it writes, especially when a page suddenly becomes slow.

Where the ORM sits

Your code talks to the ORM in objects; the ORM talks to the database in SQL. Results travel back the same path in reverse.

Four connected stages: application objects, the ORM layer, generated SQL statements, and the relational database.
Figure 1.1: application objects -> ORM -> SQL -> database

A translator at a government office

Think of a translator helping you file a form at a district office where everything must be written in the official format. You explain what you need in your own words; the translator fills in the form correctly. You save time, but if the form is rejected you still need to know what the form said. An ORM is that translator, and SQL is the form.

Turn on query logging from day one

All three ORMs can print the SQL they run: new PrismaClient({ log: ['query'] }), logging: true in a TypeORM DataSource, and the logging option in Sequelize (it logs to the console by default). Keep it on while learning. Reading the generated SQL is the fastest way to build an accurate mental model.

Quick check: Which statement about ORMs is correct?

  • An ORM stores data in its own format, so the database never sees SQL
  • An ORM generates SQL from method calls and converts the result rows back into objects
  • An ORM only works with NoSQL databases
  • An ORM makes indexes unnecessary because it caches every table in memory
Answer

An ORM generates SQL from method calls and converts the result rows back into objects — The ORM is a translation layer. The database still receives and executes ordinary SQL, so indexes, joins and query plans still matter.