r/programming 7d ago

Solving the 1+N Query Problem

https://acadia.engineering/blog/solving-the-1-plus-N-query-problem
127 Upvotes

94 comments sorted by

View all comments

64

u/disposepriority 7d ago

There is a really easy way of avoiding this when you just don't use ORMs

3

u/devraj7 7d ago

But it requires expertise in SQL.

If you use an ORM, that problem is solved automatically without you having to be a SQL expert, which is one of the points of ORMs.

WebLogic had resolved the N+1 problem in the early 2000s.

8

u/smoovewill 7d ago

SQL is a leaky abstraction. You may have to rewrite a query to something that is logically equivalent to take advantage of indexes / table structure.

But imo, ORMs are far more leaky, and I very often find I have to dig into the generated SQL / figure out how to get the ORM to emit the SQL I want (to avoid N+1 queries, to use indexes properly etc.).

I'm not dying on this hill by any means, but I strongly believe having intermediate knowledge of SQL is far more useful than having expert knowledge in an ORM (though the latter probably requires the former)

2

u/BaNyaaNyaa 3d ago

Honestly, I only like ORMs for the 90% of queries that are plainly straightforward. Get something by primary key, foreign key, simple conjunctions... As soon as there's a somewhat complex condition or a join, I want my SQL.

1

u/smoovewill 2d ago

Yea, this is basically where I land on work projects, since most people do prefer the ORM for those queries. The one thing I do try to push for is mapping query results (whether from ORM models or rows from a raw query) to plain objects (ie, dataclasses / structs / typescript interfaces), and not passing ORM objects around.