Recent posts from crabmusket.net
It's a 1+n problem, not a n+1 problem
12 Dec 2024
This is probably my most trivial tech pet peeve and I want to get it off my chest.
I have been perplexed at the common use of the term “n+1 query problem”, maybe popularised by this page on it in the SQLite docs:
Many Small Queries Are Efficient In SQLite
While the page’s content is interesting, for as long as it has been on the Wayback machine it has used the phrase “N+1 Queries Are Not A Problem With SQLite”:
https://web.archive.org/web/20240000000000*/https://sqlite.org/np1queryprob.htmlThe problem is typically caused by code that looks something like this:
// select * from posts...
$posts = Post::all();
foreach ($posts as $post) {
// select * from users where id = ...
$user = $post->author();
// use $user...
}
This code will perform a single database query returning n posts, then for each post it will run n queries, each returning one user. In the typical three-tier, remote database server setup that most webapps use, this is inefficient. (Not so when using SQLite, which is the point of their article above.) There are many ways to fix this kind of problem, depending on the framework or ORM you’re using.
Referring to this as an “n+1 problem” annoys me because the problem is that you do one query first, which is fine, then n queries afterwards, which are the problem. This phrasing emphasizes the 1, which isn’t the problem!
I wouldn’t die on this molehill, but I use the phrase “1+n problem” instead and I hope it catches on.
That's all folks! Thanks for reading ♥