What Is an ORM?
How Object-Relational Mapping Works
What is an ORM? An ORM, or object-relational mapping, is a layer of code that connects the objects used in an application to the tables and rows stored in a relational database. Instead of writing SQL for every read and write, a developer works with objects such as a Customer or an Order, and the ORM turns those actions into queries.
Most ORMs follow the same pattern. A class represents a table, each property of the class represents a column, and each instance represents one row. Saving a new customer object produces an INSERT statement, and loading a customer by ID produces a SELECT. Examples include Eloquent in Laravel, the Django ORM in Python, Prisma in TypeScript and Hibernate in Java.
Benefits: Faster Development and Easier Portability
The main benefit is productivity. Common operations need less hand-written SQL, and the code stays in the language the developer already uses. Many ORMs also handle migrations, which are tracked changes to the table structure, so the database schema evolves alongside the application.
An ORM can also make an application easier to move between database systems, because the same model code often works with MySQL, PostgreSQL or SQLite. Portability is not automatic, though. Features specific to one database, such as certain data types or functions, may still need custom code.
Pitfalls: The N+1 Query Problem and Hidden Queries
Because the ORM hides the SQL, it is easy to create performance problems without noticing. The best-known is the N+1 query problem. Suppose a page lists 50 blog posts and shows each author’s name. Loading the posts takes one query. If the code then loads each post’s author separately, the page runs 50 more queries, 51 in total. Loading the authors together with the posts, a technique often called eager loading, needs just two.
Other issues include loading far more columns or rows than a page needs, generating inefficient queries for complex reports, and hiding the cost of each action from the developer. Checking the SQL an ORM generates for important pages is good practice. Problems of this kind are a frequent cause of slow database queries.
Frequently asked questions
Do I need an ORM to use a database?
No. You can always send SQL directly to the database through a driver or client library, and many developers prefer that for complex reporting or performance-critical queries. An ORM is a convenience layer, so the choice depends on team skills, project size and how often you need custom queries.
Is an ORM slower than writing raw SQL?
It can be, but how queries are used usually matters more than the tool. An ORM adds some overhead to build queries, and patterns such as N+1 can create extra queries. A well-used ORM with eager loading and sensible schema design performs well for most websites.