Conceptual
Login

Eager Loading: Fetch the Related Rows Up Front, by JOIN or by Second Query

Eager loading is telling the ORM, before you start looping, which related objects you are going to touch, so it fetches them in one or two statements instead of one per row. There are two shapes: a JOIN that brings the parent and child back together (Django's select_related, SQLAlchemy's joinedload), and a second query with an IN-list that the ORM stitches onto the parents in memory (prefetch_related, selectinload). Use the JOIN shape for one-to-one and many-to-one, and the second-query shape for collections, because a JOIN across a one-to-many multiplies the rows you drag over the network.

Questions this Concept answers

  • Why is the join shape the wrong choice for a one-to-many collection?