Quick revision
The short answer
I would first check which joins really feed displayed columns and remove the rest, knowing that the database can only eliminate an unused LEFT JOIN itself when it joins on a unique key. Outer joins limit how the planner can reorder joins, and to-many joins multiply rows, so splitting the screen into one main query plus batched queries for optional or collection parts usually beats one wide query. Indexes on every foreign key used by a join are a must, and a read model or materialised view suits a read-heavy screen.
What to remember
In this answer, we started from the generated SQL and its plan, removed joins that feed no displayed column, using projections so the database can eliminate unique-key joins itself, and saw that outer joins restrict reordering while to-many joins multiply rows and block the limit. Splitting into a page query with to-one joins and batched IN queries for collections fixed the multiplication, indexes on foreign keys kept each part fast, and a read model remains an option for very read-heavy screens.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
I would first check which joins really feed displayed columns and remove the rest, knowing that the database can only eliminate an unused LEFT JOIN itself when it joins on a unique key. Outer joins limit how the planner can reorder joins, and to-many joins multiply rows, so splitting the screen into one main query plus batched queries for optional or collection parts usually beats one wide query. Indexes on every foreign key used by a join are a must, and a read model or materialised view suits a read-heavy screen.
Why this question is asked
ORM-generated queries grow quietly. Each optional relationship mapped as eager or fetched for convenience adds another LEFT JOIN, until one screen issues a query that joins six tables and returns thousands of rows for twenty items. When developers say all joins are needed, they mean the data is needed, which is not the same as needing it in one query. Interviewers use this scenario to see whether we diagnose with the plan and the data, rather than guessing. In this answer, we will look at the query and its plan, remove joins that feed nothing, explain why outer joins and fan-out make the planner's job harder, split the query, check indexes, and consider a read model.
1Start With the Query and the Plan
The first step is to see the actual SQL, from Hibernate's SQL log or pg_stat_statements, and its plan with EXPLAIN (ANALYZE, BUFFERS) on production-like data. Suppose the screen shows a page of 20 orders, and the generated query looks like this.
Two things stand out already. Shipments and order lines are one-to-many, so each order appears once per shipment-line combination, and the query returns far more rows than orders. And the plan shows how much time each join costs, which is where we look next.
2Remove Joins That Feed Nothing
We check each joined table against the columns the screen actually shows. Often one or two joins exist because an association is mapped as eager in the entity, @ManyToOne defaults to eager fetching in JPA, not because the screen needs it. Here, perhaps the coupon is never displayed on this list; the join can go, by making the association lazy and not fetching it for this query, or better, by selecting a DTO projection with only the columns the screen needs.
Databases can sometimes do this themselves. PostgreSQL removes a LEFT JOIN when no column of the joined table is used and the join condition matches a unique key of that table, because then the join can neither add nor remove rows. That only works if we do not select the columns, and the ORM selecting every column of every entity, the star in the SQL above, defeats it. A projection that names only needed columns lets join elimination work and shrinks every row.
3Why Outer Joins and Fan-Out Hurt the Plan
For inner joins, the planner can choose any join order, starting from the most selective table. Outer joins constrain that freedom, because the preserved side must be processed in a way that keeps its unmatched rows. With five outer joins, many good orders are simply not allowed, and the planner may end up joining large tables before applying the filter and limit.
Fan-out is the bigger cost. If an order has 3 shipments and 8 lines, the joins return 24 rows for that order, each carrying every column of the order, customer and address again. For 20 orders the database may build thousands of rows, and the ORM then deduplicates them in memory. And because the result must be sorted and limited by order, not by joined row, the database or the ORM has to process all matching rows before the limit can apply, which is the 1.85 million rows in our plan.
| Join | Cardinality | Rows added | Needed on screen? |
|---|---|---|---|
| customers | many-to-one | none (one per order) | yes: name |
| addresses | many-to-one | none | yes: city |
| coupons | many-to-one | none | no: remove |
| shipments | one-to-many | x3 on average | yes: latest status only |
| order_lines | one-to-many | x8 on average, x24 combined | yes: line count |
4Split Into Targeted Queries
The usual fix is to load the page in a few queries, each simple and well-indexed. The main query fetches 20 orders with their to-one parts, customer and address, which add no rows and can be joined safely, and applies the limit in SQL. Then one query per collection loads the needed child data for exactly those 20 ids, using IN.
6 messages in order. Play them, or step through them one at a time.
Three small queries replace one huge one, with no row multiplication and the limit applied where it belongs. In JPA, the same shape comes from DTO projections for the page plus batch fetching for collections, through @BatchSize or hibernate.default_batch_fetch_size, which loads lazy collections for many parents in one IN query instead of one query per parent. That avoids the N+1 problem that people fear when they hear lazy loading. DISTINCT ON is PostgreSQL-specific; elsewhere a ROW_NUMBER() subquery does the same.
5Indexes and a Read Model
Every foreign key used in a join should be indexed on the child side: order_lines(order_id), shipments(order_id), and for the main query an index that matches the filter and sort, such as orders(status, created_at DESC). PostgreSQL does not create indexes on foreign key columns automatically, and a missing one turns each lookup into a scan. MySQL's InnoDB requires an index on foreign key columns and creates one if needed.
If the screen is read very often and its data changes less often, a read model can be the final step: a table or materialised view holding exactly the row the screen shows, one per order with customer name, city, line count and latest shipment status, updated on writes or refreshed on a schedule. Reads become a single indexed lookup. The cost is staleness and the work of keeping it updated, so it is worth it only when the query remains a top consumer after the simpler fixes.
6Follow-up questions
Would converting the LEFT JOINs to inner joins help?
Only where the relationship is mandatory, for example every order has a customer enforced by a NOT NULL foreign key. Then an inner join is correct and gives the planner more freedom. For truly optional relationships, an inner join would drop rows and change the result.
Is a JPA entity graph a solution?
An entity graph controls what is fetched for a particular query, which helps to stop over-fetching to-one associations. But fetching collections through it produces the same join fan-out, so collections are still better loaded by batch.
How do I prove the change helped?
Compare EXPLAIN ANALYZE timings and buffers before and after, and watch the statement's total time in pg_stat_statements or the service's latency percentiles. The sum of the three new queries should be a small fraction of the old one.
7Conclusion
In this answer, we started from the generated SQL and its plan, removed joins that feed no displayed column, using projections so the database can eliminate unique-key joins itself, and saw that outer joins restrict reordering while to-many joins multiply rows and block the limit. Splitting into a page query with to-one joins and batched IN queries for collections fixed the multiplication, indexes on foreign keys kept each part fast, and a read model remains an option for very read-heavy screens.
Open with
I would start with evidence: get the actual generated SQL and run EXPLAIN ANALYZE with buffers on production-like data, then compare each joined table with what the screen actually displays.
Then, if they want more
Often a join is there only because an association is eagerly fetched, and many-to-one is eager by default in JPA, so I would make those lazy and use a DTO projection with only the needed columns.
The database can eliminate an unused LEFT JOIN on its own only when it joins on a unique key and none of its columns are selected, which selecting whole entities defeats. Then I would look at the shape.
Outer joins restrict the join orders the planner may consider, and the to-many joins, say shipments and order lines, multiply rows, so twenty orders turn into thousands of rows, and with collection fetch joins Hibernate cannot even apply the limit in SQL.
So I would split it: one page query with the to-one joins like customer and address, which add no rows, with the limit in SQL; and then one query per collection for those twenty ids with IN, returning only what the screen needs, like a line count or latest shipment status.
In JPA that is projections plus batch fetching, which avoids N+1. I would make sure every foreign key used in a join is indexed, since PostgreSQL does not do that automatically. If the screen is still hot after that, a read model or materialised view with exactly the screen's row is the last step.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, The SQL Language
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "An ORM-generated query with five LEFT JOINs for optional relationships has become the...": https://scrivio-interview-library.netlify.app/databases/sql-joins-and-subqueries/ecc34e2a7a/