r/SQL • u/badboyzpwns • May 23 '26
Discussion How do you guys handle batching to avoid n+1 besides JOINS?
For example here is the n+1 problem
// 1 query to get all surveys
const surveys = await db.query("SELECT * FROM surveys");
// then N queries — one per survey
const results = await Promise.all(
surveys.map(async (survey) => {
const employee = await db.query( // hits DB once per survey ❌
"SELECT * FROM employees WHERE id = $1",
[survey.employee_id]
);
return { ...survey, employee };
})
);
One way to solve it is with JOIN
const results = await db.query(` SELECT s.*, e.name, e.department FROM surveys s JOIN employees e ON e.id = s.employee_id `);
or WHERE IN
const employees = await db.query( `SELECT * FROM employees WHERE id IN (${employeeIds.map((_, i) => `$${i + 1}`).join(", ")})`, employeeIds );
Am I missing anything else?
7
Upvotes
8
u/jshine13371 May 23 '26
Your question is unclear, please use more words to clarify what you're actually asking.
11
u/serverhorror May 23 '26
What do you mean?
Batching as in ...?
3
u/gumnos May 23 '26
where is that list of IDs originating?
Usually you can use that as your means of sourcing the IDs directly in the subsequent query, either with an
INorEXISTSor by aJOIN21
u/workswiththeweb May 23 '26
Use a JOIN and return the full dataset the application actually needs in a single query. The N+1 issue comes from querying related data row-by-row in application code instead of letting the database perform set-based operations.
5
u/ugle May 23 '26
If you loop over a list of surveys in code and fetches them one SQL statement after another inside the loop, that is a n+1 query.
Instead you should fetch them with a single SQL statement, e.g using an IN-clause where you pass all the survey ids.
4
u/mikeblas May 24 '26
Are you done changing your question yet? If so, the JOIN statement seems pretty obviously the right way to go. I don't know why you would consider anything else.
Why would you consider anything else?
1
u/xenomachina May 24 '26
I think the reason you're getting so many people that don't know what you're talking about is that the "n+1" problem isn't really something people run into with SQL. You do a join or a sub query, and you're done.
It's only with ORMs or "no-sql" data stores where "n+1" is a common problem.
3
u/kagato87 MS SQL May 23 '26 edited May 23 '26
Just join the tables in the query.
You're getting all surveys, then getting related data on a common field. Sql is a powerhouse at this kind of thing, let it work it's magic.
(Also avoid select * outside of initial discovery of the database layout - it will bite you if the schema changes and wastes bandwidth if there are fields you don't need, while also potentially eliminating indexes that might otherwise cover your query.)
If you're using WHERE IN because you don't need anything from surveys at all, you want to switch to WHERE EXISTS. This induces a semi join, which is more performant than WHERE IN. (Every time I've tested it's faster, occasionally equivalent because the query planner IS smart enough to do that sometimes, never been slower though anything is possible.)
If you round trip, single row read, it's horrible for performance and you may even get into non-linear scaling, depending on how unlucky you are (I've seen it happen...) Every query is a round trip, and a single read is a single read. Even with perfect indexes the SQL server still reads a page, finds the one row, spits it out. Contrast with the join method, which will (usually) read each table once and figure it out from there using whatever method it thinks will be fastest.
2
u/zbignew May 23 '26
You said “besides JOINS” but joins is the canonical solution to this problem. We might could provide alternatives but they might have the same issue that is making JOIN unacceptable to you.
What’s wrong with JOIN? You haven’t described your objective or your problem, even after several edits.
4
u/rickzter May 23 '26
Joins will be the way to go for performance. Create a temp table with the ids and join it with ur employee table.
1
u/Ecksters May 24 '26 edited May 24 '26
If you're doing a data loader pattern it's common to just batch your requests with a sort of async global debounce (very short-lived, with a maximum wait time, in most JS it's essentially just a microtask queue wait) for each query, and do a big WHERE IN for the gathered up IDs.
1
u/sekharnet Aug 04 '26
Join / exists is optimal than (NOT) IN()
Join is best for 1:1
(NOT) EXISTS is best for 1:many
OR is the worst depending on DBMS