Eager Loading
ELI5 — The Vibe Check
Eager loading fetches all the related data you need upfront in one or two queries. Instead of loading a post and then separately loading its author and comments, you fetch everything together. Prevents N+1 problems. The 'include' in Prisma/Sequelize.
Real Talk
Eager loading is a strategy where associated objects are loaded as part of the initial query, using JOINs or a second IN query. It is the solution to the N+1 problem. ORMs implement it via keywords like include (Prisma), eager_load (Rails), or with (Eloquent). The trade-off is potentially fetching more data than needed.
Show Me The Code
// Prisma: eager load posts with author
const posts = await prisma.post.findMany({
include: {
author: true,
comments: { take: 5 }
}
});
When You'll Hear This
"Use eager loading to avoid the N+1 problem when fetching posts with authors." / "Eager loading everything can cause slow queries if you load too much data."
Related Terms
JOIN
JOIN combines rows from two tables based on a related column.
Lazy Loading
Lazy loading waits until you actually access related data before fetching it. Access post.author and only then does it query the database.
N+1 Query
N+1 is when your code runs 1 query to get a list of things, then runs 1 more query for EACH thing on the list.
Query Optimization
Query optimization is the art of making slow database queries fast. Add an index here, rewrite that subquery as a JOIN, fetch only the columns you need.