You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Avoid cartesian product without query splitting #22435
Query splitting was introduced, but I would personally avoid its drawbacks like the plague.
Luckily, we can usually avoid cartesian products through careful aggregate design. Still, sometimes we truly do want to join multiple 1:N relations. Of course, we would rather not risk a huge data set caused by an incidental high number of child entities.
This problem can be solved without resorting to query splitting.
As an example, say we are selecting one Parent and joining both its Sons and its Daughters.
Basically, since the joined siblings are independent, we have no reason to want them multiplied. This can be accomplished by explicitly instructing the database to keep them separate:
Join a set of constants. Since we intend to join two 1:N relations, we will join two constants: LEFT JOIN (SELECT 1 AS Id UNION ALL SELECT 2) AS Splitter.
To the Son's join condition, add: AND Splitter.Id = 1.
To the Daughter's join condition, add: AND Splitter.Id = 2.
This gives us:
SELECT*FROM Parents p
LEFT JOIN (SELECT1AS Id UNION ALLSELECT2) AS Splitter ON TRUE
LEFT JOIN Sons s ONs.ParentId=p.IdANDSplitter.Id=1LEFT JOIN Daughters d ONd.ParentId=p.IdANDSplitter.Id=2WHEREp.Id=1
While transferring a bit more data (mostly in the form of duplication of the Parent), the duplication stays linear and well under control.
When we combine careful aggregate design with avoiding the cartesian product, we have all the tools we need to load reasonable object graphs without introducing the significant drawbacks of split queries.
Reacted by bradmarder, maciejw, Nick Muller, Dan, William Roush, Andrew Scott, Steven Darby, Anton Curmanschii, Nikolai Bjørndalseter, Greg Bachraty and 2 more
@Timovzl this is definitely an interesting proposal and has the potential to improve single queries. However, note that this technique works only for multiple collection navigations being loaded at the same level; nested navigations cannot be loaded in this way, and so even if your proposal is implemented, split queries remain relevant. There are also some scenarios where your technique will cause increased data to be transferred (due to duplication of the parent rows), but I agree the benefits likely outweigh that.
In any case, the 5.0 version is now complete barring bug fixes. We'll look into this more in-depth for 6.0.
@roji I did not mean to imply that split queries will become irrelevant. Just that is really nice to have an alternative. :)
However [...] nested navigations cannot be loaded in this way
I do believe this approach can work for multiple levels of nesting as well. It can be applied as follows:
In a query, define a parent as an instance of addressing a table where one or more others are being joined onto it.
Define a child as an instance of addressing a table where it is being joined onto another. (Note that intermediate levels act as both parent and child.)
Define a 1:1 child as a child where we are certain that it can produce no more than 1 row per parent row.
Define a 1:N child as a child that is not a 1:1 child.
When applying this feature, for any parent with two or more 1:N children, apply a splitter quasi-table as demonstrated in the original post.
Some points to note: We'll need different names for each splitter quasi-table, e.g. Splitter1, Splitter2. Each one will consist of a number of rows equal to the number of children being joined.
Not only should this approach work for trees of any breadth and depth, but it should be no worse than performing the same query without it! It only applies where a cartesian product is risked, and it avoids it. I'm sure you will do tests to confirm this. I have had good results with it in practice.
As with many of EF's features, I think it would be neat if this one could be applied either per-query or on the registration of a DbContext. I can imagine wanting to use this wherever it may apply (as defined above), or simply having a single query where it comes in handy.
However [...] nested navigations cannot be loaded in this way
I do believe this approach can work for multiple levels of nesting as well
Sure. I meant to say that this technique works only for multiple collection navigations being loaded at the same level, but cannot help cases where a single navigation is loaded at each level (unless I'm missing something). For example, following your example above, if instead of a Parent with two collection navigations Sons and Daughters we have Customers, with navigation Orders, which itself has another navigation LineItems, the cartesian explosion effect still occurs when loading all customers with all their orders and line items. Unless I'm mistaken, that would still be a case where only split queries can help.
As with many of EF's features, I think it would be neat if this one could be applied either per-query or on the registration of a DbContext. I can imagine wanting to use this wherever it may apply (as defined above), or simply having a single query where it comes in handy.
This is really too early to say, but it the choice between split and single query already works this way. If we end up implementing the above mode, I don't see why it would be any different.
For example, following your example above, if instead of a Parent with two collection navigations Sons and Daughters we have Customers, with navigation Orders, which itself has another navigation LineItems, the cartesian explosion effect still occurs when loading all customers with all their orders and line items. Unless I'm mistaken, that would still be a case where only split queries can help.
You're right in that it doesn't help in this situation, whereas split queries help (at least in theory). But this scenario shouldn't warrant either. Let me illustrate.
If I'm not mistaken, the cartesian explosion is another name for the cartesian product. It refers to the multiplication effect that occurs when loading multiple types of 1:N children onto the same parent.
For example, if parent A has 100 sons and 100 daughters, there would be no single correct way to combine the sons and daughters, and so, instead, every combination is returned. Instead of 100 + 100 = 200 rows, we get 10.000! That is an explosion indeed. If loading 200 rows is acceptable, then loading 10.000 is very likely unacceptable. Note also how even a single pathological entry may cause command timeouts in the application.
In your example, by contrast, we might have 1 Customer with 5 Orders, each with 10 LineItems. The best number of entities we can hope to transfer is 1 + 1*5 + 1*5*10 = 56. The complexity is O(N), where N is the product of the counts, i.e. 1 * 5 * 10.
When we do this as a single query, we know that we get a row for each of the LineItems. Each row contains 3 entities, with the Orders and Customers potentially repeated. As such, we get 1 * 5 * 10 = 50 rows, each containing 3 entities, for a total of 150 entities transferred. The complexity is still O(N). The constant factory has simply gone up from 1.12 to 3.
I believe the takeaway here is that an increase from linear to quadratic (e.g. 200 to 10.000) is unacceptable and warrants a solution, such as split queries or the solution we are talking about here. After all, the overhead of performing multiple queries is safer and generally better than the overhead of going from 200 to 10.000 rows. However, in the latter example, there is no real explosion going on. The constant increases a bit, and we transfer a bit more data, but the overhead is generally less than that of performing multiple queries.
In conclusion, you're right that the proposed solution cannot help with nesting where no multiplication occurs, whereas split queries can, in theory. However, this situation generally needs no help.
Note that the proposed solution can help when multiplication occurs on multiple levels (like this). :)
I agree with your analysis that the problem is usually considerably more severe when the collections are on the same level, then when they are nested. However, it's important to understand that it ultimately depends on your specific scenario andBut data.
In the example with 1 Customer/5 Orders/10 LineItems, the columns for the single customer are transmitted 50 times to the client. Now, if the customer happens to have a very heavy field - such as a photo - that data gets duplicated 50 times (just for one customer). With the right data, this could easily be worse than even the 100*100 explosion of the first scenario. So any scenario where data gets duplicated is potentially very dangerous, and split queries eliminate that altogether.
But I'm not disagreeing with anything you've written above. We'd have to thoroughly benchmark your proposal across databases to make sure that there's no surprising perf issues in some scenarios (though I don't expect that would happen), and then evaluate the complexity of producing the query and materializing the results back. Beyond that I think this could be a great improvement.
An approach similar to this is already used in EF6. It works like this.
The case is where there is one parent table and at least two child tables.
Instead of doing
SELECTparent.idAS parent_id,
parent.col1AS parent_col1,
son.idAS son_id,
son.col1AS son_col1,
daughter.idAS daughter_id,
daughter.col1AS daughter_col1
FROM parent
LEFT JOIN son ONparent.id=son.parent_idLEFT JOIN daughter ONparent.id=daughter.parent_idORDER BYparent.id, son.id, daughter.id
it does the following
SELECT parent_id, parent_col1, son_id, son_col1, daughter_id, daughter_col1, c1
FROM (
(SELECT CASE WHEN (son.id IS NULL) THEN (NULL) ELSE (1) END AS c1,
parent.idAS parent_id,
parent.col1AS parent_col1,
son.idAS son_id,
son.col1AS son_col1,
NULLAS daughter_id,
NULLAS daughter_col1
FROM parent LEFT JOIN son ONparent.id=son.parent_id)
UNION ALL
(SELECT2AS c1
parent.idAS parent_id,
parent.col1AS parent_col1,
NULLAS son_id,
NULLAS son_col1,
daughter.idAS daughter_id,
daughter.col1AS daughter_col1,
FROM parent INNER JOIN daughter ONparent.id=daughter.parent_id)
) AS t
ORDER BY parent_id, c1
Don't know why it fetches all the parent columns the second time though, could easily be replaced by nulls (except for the identifier).
Reacted by Timo van Zijll Langhout, Eivind Tjore and Greg Bachraty
Provided that the database sends NULLs efficiently (such as indicated by a bit field, with no further data for that field), this has the potential to negate the effect of the multiplication almost entirely.
Of course, we'd need to confirm that the self-join is performed efficiently.
Both the EF6 strategy and the self-join strategy have the issue that the "parent" table/subquery must be evaluated twice. If it's a complicated one, you might get bad performance.
For db engines supporting APPLY / JOIN LATERAL, we can instead do the following:
SELECTp.Id, Splitter.Id, p2.*, s.*, d.*FROM Parents p
INNER JOIN (SELECT0AS Id UNION ALLSELECT1UNION ALLSELECT2) AS Splitter ON TRUE
LEFT JOIN LATERAL (SELECT p.*) p2 ONSplitter.Id=0LEFT JOIN Sons s ONs.ParentId=p.IdANDSplitter.Id=1LEFT JOIN Daughters d ONd.ParentId=p.IdANDSplitter.Id=2ORDER BYp.Id, Splitter.Id, s.Id, d.Id
In this case no data will be duplicated whatsoever (except the parent identifier).
The same approach could be used in case of just one join, if we want to avoid repeated data over the network.
Another way of avoiding duplicating the outer table for every inner row would be to add a ROW_NUMBER() OVER (PARTITION BY outer.id). We can then use CASE to replace columns with NULLs if the row number is > 1. Then add this row number != 1 as an order by item to have it emitted first.
In any case, it's a bit sad that there is no good SQL method of ordering the results so that row with common column values are grouped together. To make our shapers work correctly, we don't need a full sorted result by outer.id, but just that all rows having the same order.id are emitted consecutively. With #24360, we can eliminate some unnecessary orderings, but with any solution explained above where we also remove the duplicates from the outer table, we must add something more to order by to get the order the shapers expect, which might hurt performance at the db side, if the result set is large.
If only different db engines could identify this pattern:
SELECT*FROM
(SELECT*, ROW_NUMBER() OVER () AS rn FROM (...) AS t1) t1 -- attach an arbitrary distinct number to each row in t1LEFT JOIN
(SELECT*FROM ...) t2
ORDER BYt1.rn
then they could completely eliminate any sorting from the query plan and just perform the left join as is - i.e. emit all t2 items consecutively for each t1 item. At least PostgreSQL performs this query exactly as written, which is sad.
Just did a few manual tests and MSSQL and Oracle does seem to buffer the subqueries with the splitter table approach.
However the simple concat approach works without any buffering:
SELECT1AS SplitterId, <..vals from split query A>, <..nullfrom split query B>, <..nullfrom split query C>FROM (<split query A>)
UNION ALLSELECT2AS SplitterId, <..nullfrom split query A>, <..vals from split query B>, <..nullfrom split query C>FROM (<split query B>)
UNION ALLSELECT3AS SplitterId, <..nullfrom split query A>, <..nullfrom split query B>, <..vals from split query C>FROM (<split query C>)
This has the advantage of reusing the split query approach (assuming the split queries are independent and as far as I can tell they are), only some parameter and column shuffling is needed.
Result is as before:
1 A A null null
1 A A null null
2 null null B null
3 null null null C
3 null null null C
3 null null null C
A somewhat more complicated pattern removes many of the null regions:
SELECT a.*, b.*, c.*FROM
(
SELECT1, ROW_NUMBER() OVER (ORDER BY (SELECTNULL)) AS rn, *FROM (<split query A>)
) a
FULL JOIN
(
SELECT2, ROW_NUMBER() OVER (ORDER BY (SELECTNULL)) AS rn, *FROM (<split query B>)
) b ONa.rn=b.rn
FULL JOIN
(
SELECT3, ROW_NUMBER() OVER (ORDER BY (SELECTNULL)) AS rn, *FROM (<split query C>)
) c ON COALESCE(a.rn, b.rn)=c.rn
...
Result is
1 A A 2 B 3 C
1 A A null null 3 C
null null null null null 3 C
I imagine this is also somewhat harder to materialize without client-side buffering.
On MSSQL this plan is not so pretty with lots of overestimated row counts but the actual execution seems to be similar to the concat plan.
For Oracle substitute row_number() over(...) with rownum and the query plan is almost identical to the concat plan.
On a related note why was the EF6 strategy (concat siblings) abandoned?
On MSSQL this plan is not so pretty with lots of overestimated row counts but the actual execution seems to be similar to the concat plan.
We'd indeed need to do a more thorough check on how all the above ideas impact the query plans - and do that across the different databases rather than just MSSQL. Intuitively I don't necessarily foresee a problem, but this must be thoroughly verified.
Can the client stream the data? As far as I can tell Oracle does efficient wire encoding (Oson) but still allocates a single large buffer, causing memory pressure.
Support for json is also relatively new and likely provider specific. Alternatives could be xml and nested tables but those could have the same problems.
Plain old tabular data behavior on the other hand is much better understood. It feels like a lower hanging fruit.
Activity
roji commentedon Sep 9, 2020
@Timovzl thanks for this proposal, we'll study this and respond soon.
roji commentedon Sep 12, 2020
@Timovzl this is definitely an interesting proposal and has the potential to improve single queries. However, note that this technique works only for multiple collection navigations being loaded at the same level; nested navigations cannot be loaded in this way, and so even if your proposal is implemented, split queries remain relevant. There are also some scenarios where your technique will cause increased data to be transferred (due to duplication of the parent rows), but I agree the benefits likely outweigh that.
In any case, the 5.0 version is now complete barring bug fixes. We'll look into this more in-depth for 6.0.
roji commentedon Sep 12, 2020
Note when investigating - do actual cross-database benchmarks to measure and compare perf.
Timovzl commentedon Sep 13, 2020
@roji I did not mean to imply that split queries will become irrelevant. Just that is really nice to have an alternative. :)
I do believe this approach can work for multiple levels of nesting as well. It can be applied as follows:
Some points to note: We'll need different names for each splitter quasi-table, e.g.
Splitter1,Splitter2. Each one will consist of a number of rows equal to the number of children being joined.Not only should this approach work for trees of any breadth and depth, but it should be no worse than performing the same query without it! It only applies where a cartesian product is risked, and it avoids it. I'm sure you will do tests to confirm this. I have had good results with it in practice.
As with many of EF's features, I think it would be neat if this one could be applied either per-query or on the registration of a DbContext. I can imagine wanting to use this wherever it may apply (as defined above), or simply having a single query where it comes in handy.
roji commentedon Sep 13, 2020
Sure. I meant to say that this technique works only for multiple collection navigations being loaded at the same level, but cannot help cases where a single navigation is loaded at each level (unless I'm missing something). For example, following your example above, if instead of a Parent with two collection navigations Sons and Daughters we have Customers, with navigation Orders, which itself has another navigation LineItems, the cartesian explosion effect still occurs when loading all customers with all their orders and line items. Unless I'm mistaken, that would still be a case where only split queries can help.
This is really too early to say, but it the choice between split and single query already works this way. If we end up implementing the above mode, I don't see why it would be any different.
Timovzl commentedon Sep 14, 2020
You're right in that it doesn't help in this situation, whereas split queries help (at least in theory). But this scenario shouldn't warrant either. Let me illustrate.
If I'm not mistaken, the cartesian explosion is another name for the cartesian product. It refers to the multiplication effect that occurs when loading multiple types of 1:N children onto the same parent.
For example, if parent A has 100 sons and 100 daughters, there would be no single correct way to combine the sons and daughters, and so, instead, every combination is returned. Instead of 100 + 100 = 200 rows, we get 10.000! That is an explosion indeed. If loading 200 rows is acceptable, then loading 10.000 is very likely unacceptable. Note also how even a single pathological entry may cause command timeouts in the application.
In your example, by contrast, we might have 1 Customer with 5 Orders, each with 10 LineItems. The best number of entities we can hope to transfer is
1 + 1*5 + 1*5*10 = 56. The complexity is O(N), where N is the product of the counts, i.e.1 * 5 * 10.When we do this as a single query, we know that we get a row for each of the LineItems. Each row contains 3 entities, with the Orders and Customers potentially repeated. As such, we get
1 * 5 * 10 = 50rows, each containing 3 entities, for a total of 150 entities transferred. The complexity is still O(N). The constant factory has simply gone up from 1.12 to 3.I believe the takeaway here is that an increase from linear to quadratic (e.g. 200 to 10.000) is unacceptable and warrants a solution, such as split queries or the solution we are talking about here. After all, the overhead of performing multiple queries is safer and generally better than the overhead of going from 200 to 10.000 rows. However, in the latter example, there is no real explosion going on. The constant increases a bit, and we transfer a bit more data, but the overhead is generally less than that of performing multiple queries.
In conclusion, you're right that the proposed solution cannot help with nesting where no multiplication occurs, whereas split queries can, in theory. However, this situation generally needs no help.
Note that the proposed solution can help when multiplication occurs on multiple levels (like this). :)
roji commentedon Sep 14, 2020
I agree with your analysis that the problem is usually considerably more severe when the collections are on the same level, then when they are nested. However, it's important to understand that it ultimately depends on your specific scenario andBut data.
In the example with 1 Customer/5 Orders/10 LineItems, the columns for the single customer are transmitted 50 times to the client. Now, if the customer happens to have a very heavy field - such as a photo - that data gets duplicated 50 times (just for one customer). With the right data, this could easily be worse than even the 100*100 explosion of the first scenario. So any scenario where data gets duplicated is potentially very dangerous, and split queries eliminate that altogether.
But I'm not disagreeing with anything you've written above. We'd have to thoroughly benchmark your proposal across databases to make sure that there's no surprising perf issues in some scenarios (though I don't expect that would happen), and then evaluate the complexity of producing the query and materializing the results back. Beyond that I think this could be a great improvement.
8 remaining items
Emill commentedon Mar 1, 2021
An approach similar to this is already used in EF6. It works like this.
The case is where there is one parent table and at least two child tables.
Instead of doing
it does the following
Don't know why it fetches all the parent columns the second time though, could easily be replaced by nulls (except for the identifier).
Emill commentedon Mar 10, 2021
Both the EF6 strategy and the self-join strategy have the issue that the "parent" table/subquery must be evaluated twice. If it's a complicated one, you might get bad performance.
For db engines supporting APPLY / JOIN LATERAL, we can instead do the following:
In this case no data will be duplicated whatsoever (except the parent identifier).
The same approach could be used in case of just one join, if we want to avoid repeated data over the network.
Emill commentedon Mar 14, 2021
Another way of avoiding duplicating the outer table for every inner row would be to add a ROW_NUMBER() OVER (PARTITION BY outer.id). We can then use CASE to replace columns with NULLs if the row number is > 1. Then add this row number != 1 as an order by item to have it emitted first.
In any case, it's a bit sad that there is no good SQL method of ordering the results so that row with common column values are grouped together. To make our shapers work correctly, we don't need a full sorted result by outer.id, but just that all rows having the same order.id are emitted consecutively. With #24360, we can eliminate some unnecessary orderings, but with any solution explained above where we also remove the duplicates from the outer table, we must add something more to order by to get the order the shapers expect, which might hurt performance at the db side, if the result set is large.
If only different db engines could identify this pattern:
then they could completely eliminate any sorting from the query plan and just perform the left join as is - i.e. emit all t2 items consecutively for each t1 item. At least PostgreSQL performs this query exactly as written, which is sad.
bachratyg commentedon Jul 16, 2025
Just did a few manual tests and MSSQL and Oracle does seem to buffer the subqueries with the splitter table approach.
However the simple concat approach works without any buffering:
This has the advantage of reusing the split query approach (assuming the split queries are independent and as far as I can tell they are), only some parameter and column shuffling is needed.
Result is as before:
A somewhat more complicated pattern removes many of the null regions:
Result is
I imagine this is also somewhat harder to materialize without client-side buffering.
On MSSQL this plan is not so pretty with lots of overestimated row counts but the actual execution seems to be similar to the concat plan.
For Oracle substitute
row_number() over(...)withrownumand the query plan is almost identical to the concat plan.On a related note why was the EF6 strategy (concat siblings) abandoned?
roji commentedon Jul 17, 2025
We'd indeed need to do a more thorough check on how all the above ideas impact the query plans - and do that across the different databases rather than just MSSQL. Intuitively I don't necessarily foresee a problem, but this must be thoroughly verified.
davidroth commentedon Jul 17, 2025
@bachratyg Also have a look at the following issue, which looks like the most promising solution for solving this problem:
Consider a related entity loading strategy that aggregates dependent collections to a JSON array
bachratyg commentedon Jul 18, 2025
Protocol overheads to consider:
MSSQL: 1 bit for each cell. NBCROW packet contains a null bitmap. Overhead is likely tiny.
Oracle: the TTC spec is internal/proprietary, but sporadic information points to the existence of a column presence bitmap, so probably same as MSSQL
PG: 4 bytes for each null cell (see DataRow here). Null bitmaps were deliberately discontinued. This overhead could be alarming.
MySql: 1 byte for each null cell (see here). The rest of the data is textual thus quite bulky so this should have less impact than PG.
There is also SSL compression support for some providers, but that is being phased out due to security concerns.
bachratyg commentedon Jul 18, 2025
I'm not sure about this. At first glance it looks like the clean and mean way but several issues need to be addressed first:
Support for json is also relatively new and likely provider specific. Alternatives could be xml and nested tables but those could have the same problems.
Plain old tabular data behavior on the other hand is much better understood. It feels like a lower hanging fruit.