tezvyn:

Eager vs lazy loading in an ORM

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

ORM loading strategy.

OUTLINE

eager fetches related data up front (joins/extra query); lazy defers until accessed. Lazy in a loop causes the N+1 query problem.

RED FLAG

not naming N+1 or thinking eager is always cheaper.

WHAT THIS TESTS Whether you understand the tradeoff between fetching related data up front versus on demand, and can recognize the N+1 query antipattern.

A GOOD ANSWER COVERS Eager loading retrieves a parent entity together with its related entities in the same operation, typically through a SQL join or a single follow-up query batching the related rows. It avoids repeated database round trips when you know you will use the relationships, but it can over-fetch data you never touch and produce large joins. Lazy loading defers loading a relationship until the code actually accesses that attribute, issuing a separate query at that moment. Lazy is efficient when relationships are often unused, but dangerous when you iterate. The wrong choice surfaces as the N+1 query problem: you load N parent rows in one query, then access a lazy relationship on each inside a loop, triggering N additional queries, one per parent. For 1000 orders, listing each order's customer lazily fires 1001 queries instead of one or two.

COMMON WRONG ANSWERS Saying eager is always faster, missing the N+1 pattern, or conflating eager loading with caching.

LIKELY FOLLOW-UPS How to fix N+1 with a join fetch or batched IN query; how select-in versus join-based eager loading differ; when over-fetching from eager loading hurts.

ONE CONCRETE EXAMPLE An order-list page loops over 500 orders and reads order.customer.name, with the customer relationship configured lazy. This fires the initial orders query plus 500 single-row customer queries, 501 total, and the page crawls. Switching to eager loading with a join, or batching the customers in one IN query, collapses it to one or two queries and the page becomes fast.

Read the original → docs.sqlalchemy.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.