Skip to content

ORM vs raw SQL: the spectrum between them, N+1, cartesian explosion, injection and how to decide

From a driver with raw SQL to a full ORM, through micro-ORMs and query builders, in Node, .NET and Java: the classic problems on each side, migrations and the Prisma warning of 2026.

Ramon Gomes 12 min read Level: Intermediate

Also available in: Español, Français, Português

"ORM or raw SQL?" is one of the oldest debates in back-end work, and it's almost always framed as a single choice for the whole project. It isn't. This portfolio, for example, uses Prisma 7 for CRUD and hand-written SQL where the query reads more clearly that way.

This article shows the spectrum of options in Node/TypeScript, .NET and Java, the classic problems on each side (N+1, cartesian explosion, injection) and a practical rule for deciding. I checked the versions against the official registries on November 21, 2026.

Simultaneous interpretation booth with an interpreter wearing headphones in front of the microphone, seen through the glass facing the auditorium, low light
The interpreter handles most of the conversation. In a delicate negotiation, you want to speak the language.

The Original Problem

In 2006, Ted Neward wrote that "Object/Relational Mapping is the Vietnam of Computer Science": "a quagmire which starts well, gets more complicated as time passes", with "no clear exit strategy". The reason is that objects and tables are models that "are simply too different to bridge silently". Objects have inheritance, references and collections; tables have rows, keys and joins.

Six years later, Martin Fowler answered in "OrmHate" with a more balanced view: "The object/relational mapping problem is hard", but "the ORM can handle about 80-90% of the mapping problems", and the tools "deserve a little more respect and a lot more understanding."

Both views still hold. The ORM handles most of it well, and the remaining 10% is where the pain lives.

The Spectrum: From Raw SQL to a Full ORM

Isometric route with four stations: raw SQL (pg, JDBC, ADO.NET), micro-ORM (Dapper, MyBatis), query builder (Kysely, jOOQ), and ORM (Prisma, EF Core, Hibernate). Bars indicate less SQL control and more productivity toward ORM.
The further right, the more the tool writes for you and the less you control the SQL.
Level What it does Node/TS .NET Java
Raw SQL You write the SQL, the driver sends it with parameters pg, postgres.js ADO.NET JDBC, Spring JdbcClient
Micro-ORM You write the SQL, it maps the result to objects (rarely used) Dapper 2.1 MyBatis 3.6
Query builder Typed API that builds the SQL; no stateful entities Kysely 0.29 (LINQ to DB) jOOQ 3.21
ORM Maps tables to classes, generates SQL, tracks changes, creates migrations Prisma 7.10, Drizzle 0.45, TypeORM 1.1, MikroORM 7.2 EF Core 11 Hibernate 7.4 (JPA 3.2)

Drizzle sits in an interesting middle ground: the docs say "If you know SQL, you know Drizzle", and the query APIContract that defines how one program asks another for data or actions: which endpoints to call, what to send and what comes back. On the web, usually HTTP with JSON. looks a lot like SQL itself.

The Same Request at Each Level

Fetching a user by id, in TypeScript:

ts
// Raw SQL (postgres.js): the value goes in as a parameter, not as text
const [user] = await sql`select id, name from users where id = ${id}`;

// Query builder (Kysely)
const user = await db.selectFrom('users').select(['id', 'name'])
  .where('id', '=', id).executeTakeFirst();

// Lightweight ORM (Drizzle)
const [user] = await db.select().from(users).where(eq(users.id, id));
// select "id", "name" from "users" where "users"."id" = $1; -- params: [42]

// ORM (Prisma 7)
const user = await prisma.user.findUnique({ where: { id } });

In C# and Java:

csharp
// Dapper: you write the SQL, it fills the object
var user = conn.QuerySingle<User>("select id, name from users where id = @Id", new { Id = id });

// EF Core
var user = await db.Users.FindAsync(id);
java
// Spring JdbcClient (raw SQL with a named parameter)
User u = jdbcClient.sql("select id, name from users where id = :id")
    .param("id", id).query(User.class).single();

// Spring Data JPA: the method name becomes the query
Optional<User> findById(Long id);

For a lookup by id, they're all fine. The difference shows up when the query grows.

Classic Problem 1: N+1

This is the famous one. You load a list and, for each item, the code fetches something related. Result: 1 query for the list and N extra queries.

ts
const posts = await prisma.post.findMany();          // 1 query
for (const post of posts) {
  post.author = await prisma.user.findUnique({       // + 1 per post
    where: { id: post.authorId },
  });
}
Two cards with five posts and a database compare N+1 and include. An initial query and five lookups total 6 database trips; with include, the grouped list uses just 1 trip.
Six trips to fetch what fit in one.

The EF Core docs call this the N+1 problem and say "it can cause very significant performance issues." That's why they recommend avoiding lazy loading, which makes it far too easy to trigger without noticing. The Hibernate docs go the same way: "Almost all associations should be lazy", but whatever you're going to use should be fetched explicitly in the query.

The fix is to ask for the relationship up front:

ts
const posts = await prisma.post.findMany({ include: { author: true } });
csharp
var posts = await db.Posts.Include(p => p.Author).ToListAsync();

N+1 is bad in an ORM and in raw SQL. The difference is that, in an ORM, it hides behind a property that looks like an ordinary field.

Cartoon of a sweaty waiter running from the kitchen to a table of twenty people bringing one plate at a time, while another waiter in the background calmly arrives with a full tray
Twenty trips to the kitchen, or one tray.

Classic Problem 2: Cartesian Explosion

The opposite of N+1 hurts too. When you include two collections at the same level in a single query, the database returns every combination. The EF Core docs give the example: "if a given blog has 10 posts and 10 contributors, the database returns 100 rows for that single blog."

A blog has three posts and three contributors. A three-by-three matrix shows all nine combinations, with the blog repeated in each cell. Beside it, AsSplitQuery separates two queries with three records each: 3 + 3 = 6 rows.
Two collections in the same query multiply the rows.
csharp
var blogs = await db.Blogs
    .Include(b => b.Posts)
    .Include(b => b.Contributors)
    .AsSplitQuery()          // one query per collection
    .ToListAsync();

A split query fixes it, but trades the problem for others: more round trips to the database and no guarantee that the queries see the same moment of the data. There's no free lunch; there's choosing with the cost in view.

Classic Problem 3: Tracking You Didn't Ask for

ORMs like EF Core and Hibernate keep a "snapshot" of every loaded entity, so they know what changed when it's time to save. That's great when you're going to change the data, and wasteful when you're only reading.

Sequence with a database, User #7, and a snapshot: the entity shows Ana Lima while the snapshot keeps Ana and the same email. UPDATE changes only the name. In the AsNoTracking panel, Ana arrives without a snapshot and the memory bar is shorter.
The snapshot is there for saving later. For reading only, it's dead weight.

In the benchmark from the EF Core docs themselves, the same query with AsNoTracking took about 30% less time and used less memory. For list screens and reports, reading without tracking is usually the right default.

SQL Injection: The ORM Isn't an Automatic Shield

According to OWASP, the defense against injection is the parameterized query: the user's value travels separately from the SQL text. ORMs do this by default in their regular APIs. The risk lives in the exits to raw SQL.

The browser contains the search quote OR 1 equals 1. Two paths lead to the database: concatenated, the text becomes part of SQL and returns every row; parameterized, the command uses $1 and the text stays in a separate envelope as a value, returning 0 rows.
Concatenated, the text becomes a command. As a parameter, it's just a value.
Tool Safe Dangerous if used with user text
Prisma $queryRaw with a template, TypedSQL $queryRawUnsafe, $executeRawUnsafe
EF Core FromSql($"... {value}"), ExecuteSql FromSqlRaw, ExecuteSqlRaw with concatenation
Hibernate/JPA Named parameters in HQL HQL built with +
postgres.js Template sql\...${value}`` sql.unsafe(text)

One detail that fools people: in EF Core, FromSql($"... {user}") looks like string interpolation, but EF turns each {} into a parameter. FromSqlRaw($"...") with the same syntax, on the other hand, is real concatenation.

And a limit that applies to all of them: table names, column names and ASC/DESC can't be parameters. If the user picks the sort column, check it against a fixed list of allowed values before building the SQL.

When the ORM Gets in the Way, Go Down a Level (Without Leaving It)

The modern way out isn't switching tools, it's using the escape hatch the tool gives you:

  • Prisma TypedSQL: you write the query in a .sql file, run prisma generate --sql and call it with generated types. The Prisma docs recommend TypedSQL over the old raw queries.
  • EF Core: FromSql for entities, SqlQuery<T> for types that aren't entities (since EF Core 8).
  • Spring: @Query(nativeQuery = true) on the repository, or JdbcClient alongside JPA.
sql
-- prisma/sql/authorsWithTotal.sql
SELECT u.id, u.name, COUNT(p.id) AS "totalPosts"
FROM "User" u
LEFT JOIN "Post" p ON p."authorId" = u.id
GROUP BY u.id, u.name
ts
import { authorsWithTotal } from './generated/prisma/sql';
const rows = await prisma.$queryRawTyped(authorsWithTotal());  // rows already typed

That's exactly the "use both" from the Hibernate introduction: the ORM where it shines, SQL where SQL is clearer.

Migrations: The Part That Matters Most in the Long Run

How you query is reversible. How you evolve the schema, less so. Each ecosystem has its own tool:

Stack Tool How it works
Prisma Prisma Migrate Compares schema.prisma with the database and generates SQL
Drizzle drizzle-kit generate creates SQL from the TS schema; push applies it directly (prototyping)
.NET EF Core Migrations Migrations in C#; EF 11 records the id of the last migration to flag conflicts between branches
Java Flyway 13, Liquibase 5 Versioned SQL files (V2__add_column.sql) or changesets

Two rules apply to all of them: read the generated SQL before applying it in production, and do destructive migrations in steps (add, copy, switch, and only then remove).

The Prisma Warning for 2026

If you use Prisma, watch out for a version trap. On November 21, 2026, the npm latest tag points to Prisma 8.0.0-rc.34, a release candidate. Prisma's own status page warns: "npm install prisma and npx prisma now give you the Prisma ORM 8 command-line tool, which does not read schema.prisma and has no generate, migrate dev, or db push commands."

To stay on 7:

sh
npm install --save-dev prisma@7
npm install @prisma/client@7

And pin "prisma": "^7" in package.json. Prisma 7 gets fixes for 18 months after 8 ships officially. Other ecosystems changed too: EF Core 8 and 9 went out of support on November 10, 2026, and Drizzle 1.0 is still in RC.

How to Decide

Situation Leaning
CRUD with many entities, mixed team ORM
Team strong in SQL, analytical queries Query builder or raw SQL with parameters
.NET with heavy read queries EF Core for writes, Dapper for reads
Enterprise Java JPA/Hibernate, with jOOQ or native SQL for reports
Serverless or edge with sensitive cold starts Lightweight ORM (Drizzle) or the driver directly
Any case Know how to read the SQL the tool generates

The last row is the one that matters most. A dev who reads the ORM's SQL log fixes in minutes the N+1 someone else would spend days hunting. Turn on query logging in development, always.

Quick check

1. You list 50 orders and, in a loop, fetch each one's customer. How many queries does that generate?
Show answer

Answer: 51

It's N+1: one for the list and one per order. The fix is to load the customer along with it.

2. In EF Core, which of these calls is vulnerable if it receives concatenated user text?
Show answer

Answer: FromSqlRaw("... " + value)

FromSql turns the interpolation into a parameter. FromSqlRaw uses the text as it comes.

3. What does the official Hibernate introduction say about the goal of ORM?
Show answer

Answer: Not to hide SQL, and to use ORM and hand-written SQL together

The authors themselves recommend both, each where it pays off most.

Frequently Asked Questions

Does an ORM make the application slow?

Not by itself. What makes it slow is N+1, loading too many columns and rows, and unnecessary tracking. With SQL logging on, these show up early.

Prisma or Drizzle?

Prisma has its own schema, mature migrations and a high-level API. Drizzle has its schema in TypeScript, a SQL-like API and zero dependencies. Both work; Drizzle appeals more to people who think in SQL.

Is Dapper faster than EF Core?

For simple read queries, it usually is, and many teams use both together. But modern EF Core with AsNoTracking and projection narrows the gap a lot. Measure it in your own case.

Can I switch ORMs later?

You can, but it costs. Queries are spread across the code. Keeping data access in repositories or services makes switching, and testing, easier.

What about stored procedures?

They're still valid, and every ORM can call them. Just remember that parameters protect the call, not the dynamic SQL built inside the procedure.

References

Checked on November 21, 2026:

Source: https://ramongomessilva.com.br/blog/orm-vs-raw-sql · Accessed on December 02, 2026

Share Share on LinkedIn Share on X
Cite this article

Ready-made reference, with today as the access date.

ABNT

Brazilian standard (NBR 6023). Use it in theses and academic papers submitted in Brazil.

GOMES, Ramon. ORM vs raw SQL: the spectrum between them, N+1, cartesian explosion, injection and how to decide. Ramon Gomes, 30 nov. 2026. Disponível em: https://ramongomessilva.com.br/blog/orm-vs-raw-sql. Acesso em: 2 dez. 2026.

APA

American Psychological Association style. Common in scientific papers and journals, especially in the social, behavioral and health sciences.

Gomes, R. (2026, November 30). ORM vs raw SQL: the spectrum between them, N+1, cartesian explosion, injection and how to decide. Ramon Gomes. https://ramongomessilva.com.br/blog/orm-vs-raw-sql

BibTeX

Format for LaTeX users (Overleaf, for example). Paste it into your .bib file or import it into Zotero or Mendeley.

@online{gomes2026ormvsraw,
  author = {Gomes, Ramon},
  title = {{ORM vs raw SQL: the spectrum between them, N+1, cartesian explosion, injection and how to decide}},
  organization = {Ramon Gomes},
  year = {2026},
  month = nov,
  date = {2026-11-30},
  url = {https://ramongomessilva.com.br/blog/orm-vs-raw-sql},
  urldate = {2026-12-02}
}
Found a mistake?

Wrong fact, broken link, outdated information: tell me and I will fix it.

10 to 2,000 characters. If you can, point to the right source.

Only so I can reply. It never shows on any page of the site.

Written by

Ramon Gomes

Software Engineer

Full stack software engineer. I like taking a messy problem, listening to the people who live with it and shipping something that holds up day to day. These days I split my time between my own products, applied AI and client work.

Available for projects

Need Something Like This Built?

I build websites, systems, apps and AI automations, from design to deploy. Tell me what you need or see what I offer.

Related Articles