What an ORM Is, and Should a Beginner Use One?

Frameworks often come with an ORM, and tutorials may use it from the first lesson. Beginners then wonder whether they need SQL at all. This page explains what an ORM is, what it does well, where it surprises people and how to approach it while learning.

The idea

ORM stands for object-relational mapper. It maps rows in database tables to objects in your programming language. Instead of writing SQL, you write code that looks like ordinary objects and methods, and the ORM writes the SQL for you.

A tiny example

With plain SQL in Python:

rows = conn.execute("SELECT id, title FROM books WHERE author = ?", ("Le Guin",)).fetchall()

With an ORM such as Django's:

books = Book.objects.filter(author="Le Guin")

Behind the scenes, Django sends a SELECT with a WHERE clause and a placeholder, then turns each row into a Book object.

What ORMs do well

Where they surprise beginners

Hidden queries. Accessing book.author.name may quietly run another query. In a loop over a hundred books, that can mean a hundred extra queries. This is the famous "N+1" problem.

Not knowing what was sent. When something is slow or wrong, you need to see the SQL. Most ORMs can print the queries they run; learn how to switch that on early.

Raw SQL escape hatches. ORMs let you write raw SQL for special cases. If you glue user input into those strings, you lose the protection placeholders give.

Common ORMs by language

LanguageExamples
PythonDjango ORM, SQLAlchemy
RubyActive Record (Rails)
JavaScript and TypeScriptPrisma, Sequelize, TypeORM
JavaHibernate and other JPA implementations
C#Entity Framework Core

So, should a beginner use one?

Learn the basics of SQL first, or at least alongside: SELECT, WHERE, JOIN, INSERT, UPDATE, DELETE, and keys. Then use your framework's ORM with confidence, because you will understand what it is doing for you. Many developers write ORM code most days and still rely on SQL knowledge whenever something goes wrong.

A good habit

Whenever you write an ORM query, turn on query logging and look at the SQL it produced at least once. Ask yourself whether you would have written something similar. It is the fastest way to learn both the ORM and SQL together.

Where next

Our essay on database drivers explains the layer underneath the ORM, and the CRUD do and don't page applies whether you write SQL or ORM code.

A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.

Related pages on this site