Skip to main content

What Is an ORM? How Your Code Talks to a Database Without Writing SQL

Updated 7 min readMarkdown

To put it simply, an ORM is a translator that sits between your code and your database, so you can work with database rows as if they were ordinary objects in your programming language. ORM stands for object-relational mapping, which sounds academic, but the job is simple: it turns a row in a table into an object you can use, and turns an object back into a row when you save it.

The short version: instead of writing SQL strings inside your code, you write normal code with classes and attributes, and the ORM writes the SQL for you. You ask for users in Yangon, it writes the SELECT. You change a name, it writes the UPDATE.

How an ORM sits between your code and your database

The interpreter at the table

I think of an ORM the way I think of an interpreter at a business meeting. Two people need to work together, but they speak different languages. The programmer speaks in objects and methods. The database speaks in tables, rows, and SQL. Without an interpreter, the programmer has to learn the database's language and write every sentence by hand, in SQL strings, pasted into the code. With one, the programmer just talks normally, and the interpreter handles the translation both ways.

That translation is doing more work than it looks like. A database stores a user as a row: an id, a name, a city, a number for the account balance. Your code wants a user as an object: user.name, user.city, user.balance. The ORM maps one to the other. It knows that the users table matches the User class, that the city column matches the city attribute, and that when you save the object, it should become an UPDATE statement. It also knows about relationships. A user has many orders, an order belongs to one user, and the ORM turns those links into attributes you can follow, instead of JOINs you have to write by hand.

Here is the smallest version that works, in Python with SQLAlchemy, one of the most widely used ORMs in the Python world:

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True)
    name = Column(String)
    city = Column(String)

users_in_yangon = session.query(User).filter_by(city="Yangon").all()

That last line is the whole point. No SQL string, no manual connection handling, no turning rows into objects by hand. The ORM writes the equivalent of SELECT * FROM users WHERE city = 'Yangon' and hands you back a list of User objects you can use like any other Python objects. Change one and save it, and the ORM writes the UPDATE for you.

From code to database row and back

You write objects, the ORM writes SQL, the database answers in rows, and the ORM turns them back into objects.

What it saves you, and what it costs

The honest version of this story has two sides, because an ORM is a trade, not a free lunch. On the good side, it removes a whole class of silly mistakes. Hand-written SQL inside code is where SQL injection bugs used to hide — the kind of bug I wrote about earlier, where a text box can break a whole website. An ORM builds its queries with parameters, so user input stays data and never becomes code. It also makes the code easier to read. session.query(User).filter_by(city="Yangon") tells you what is happening in plain words. The SQL version tells you too, but it reads like a different language dropped into the middle of your Python file.

It also makes switching databases less painful. The same ORM code can often talk to PostgreSQL on your server and SQLite on your laptop, because the ORM knows the small differences between them and hides them from you. That is genuinely useful in real projects, where the database on your machine is almost never the database in production.

But the cost is real, and it has a name you will hear the moment you use an ORM seriously: the N+1 problem. Say you load 100 users, and then for each user you ask for their orders. Without thinking about it, your code makes one query for the users, then one more query per user — 101 queries to show one page. The ORM did exactly what you asked. It just did it in the slowest possible way, and nothing in your code warned you. The fix is to tell the ORM to load the orders together with the users, in one joined query. But you have to know the problem exists before you can fix it, and the first time it bites you is usually in production, on a page that suddenly takes eight seconds to load.

Put side by side, the difference is easy to see:

Raw SQL ORM
Writing queries You write every statement by hand You write code, it writes the SQL
Reading the code SQL strings inside your language Plain objects and attributes
Safety Easy to slip in an injection bug Parameters built in by default
Speed surprises You see every query you wrote N+1 queries can hide from you
Learning Must learn SQL well Must learn the ORM's habits

The verdict is not that one side wins. It is that an ORM trades visible SQL for invisible queries, and you have to keep an eye on what it actually sends to the database. Most ORMs have a way to print the SQL they generate, and turning that on while you learn is the single best habit I can suggest. The moment you see what your innocent-looking line of code actually asked the database to do, you start writing better ORM code.

When to reach for one

For a small script that reads one table once, an ORM is overkill. A few lines of SQL, or even a plain file, will do. The ORM earns its place when an app grows: many tables, relationships between them, and the same queries written over and over. That is when the translation work starts to feel like real work, and handing it to a library frees you to think about the app itself.

The other time it earns its place is on a team. SQL written by five different people in five different styles, scattered through the code, is hard to review and hard to change. ORM code has one shape, one place where the model is defined, and one way to ask a question. That consistency is worth more than it sounds like when you are reading someone else's code at 11 p.m.

I still write raw SQL sometimes, for a report query or a tricky aggregation where the ORM would fight me. That is normal. The ORM is the default, and raw SQL is the escape hatch for the awkward 5 percent. Knowing both is the skill. Knowing only one of them is how you end up blaming the tool for a problem your own code caused.

So the next time you see a class in a codebase that looks like a database table wearing a costume, you will know what it is. It is not the database. It is the translator, standing between your code and the database, doing the talking so you don't have to.

Raw SQL and an ORM, side by side

Raw SQL gives you full control; an ORM gives you objects and safety by default. Most projects use both.

References and further reading

— Min SiThu Software Engineer & Tech Content Creator https://minsithu.org

About the author

  • Nubbad Developer. | Now I accidentally create problems.

No comments yet. Be the first to comment.