Skip to content

Commit 23da400

Browse files
authored
Include a preload joins vs. no joins discussion in the preload docs (#4517)
1 parent 4cc725a commit 23da400

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

lib/ecto/query.ex

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2667,6 +2667,30 @@ defmodule Ecto.Query do
26672667
where: l.inserted_at > c.updated_at,
26682668
preload: [:author, comments: {c, likes: l}]
26692669
2670+
## Choosing between preloading with joins vs. separate queries
2671+
2672+
Deciding between preloading associations via joins, a single large
2673+
query, (`preload: [comments: c]`) or separate smaller queries
2674+
(`preload: [:comments]`) depends on the specific use case.
2675+
Here are some factors to guide your decision:
2676+
2677+
* **Joins reduce database round trips:** By fetching data in a single
2678+
query, joins can minimize database round trips, potentially reducing
2679+
overall latency.
2680+
* **Potential for data duplication:** Joins may lead to duplicated
2681+
data in the result set, which requires more processing by Ecto
2682+
and consumes more bandwidth when transmitting the results.
2683+
* **Parallelism with separate queries:** When using separate queries
2684+
outside of a transaction, Ecto can parallelize the preload queries,
2685+
which can speed up the overall operation.
2686+
2687+
In general, a good default is to only use joins in preloads if you're
2688+
already joining the associations in the main query. For example,
2689+
in the last query in the section above, comments and likes are already
2690+
joined, so they are included in the preload.
2691+
However, the author is not joined in the main query, so it is preloaded
2692+
via a separate query.
2693+
26702694
## Preload queries
26712695
26722696
Preload also allows queries to be given, allowing you to filter or

0 commit comments

Comments
 (0)