Re:Understanding N + 1 queries problem
by keltex on Monday January 02, 2023 @02:17PM
(#34222337)
I don't know Rails Active Record. But if the ORM is anything like others I am more familiar with (Django / Python or Linq / C#) can't you do a join and just have a single query? Or use raw SQL if performance is an issue?
[ Parent
| on HN ]
I don't know ActiveRecord either, but it appears so https://guides.rubyonrails.org/active_record_querying.html#j...
Re:Understanding N + 1 queries problem
by acjohnson55 on Monday January 02, 2023 @02:28PM
(#34222470)
The problem tends to come up when you pass models around and subsequent logic traverses relationships. It's fundamentally an issue of treating Active Record-style models as though they were in-memory objects.
Re:Understanding N + 1 queries problem
by jbverschoor on Monday January 02, 2023 @04:04PM
(#34223630)
No it's not. If one forehand you do not know which "object graph" you need, you'll run in this problem no matter what the underlying tech is.
At least some with ORMs you can specify afterwards (when passing the activerecords) that you want to have prefetched (inner or outer joins, caching). Sometimes it's done automatically, because you can simply detect when you're in an N+1 query loop.