Skip to content

Avoid cartesian product without query splitting #22435

Description

@Timovzl

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 (SELECT 1 AS Id UNION ALL SELECT 2) AS Splitter ON TRUE
LEFT JOIN Sons s ON s.ParentId = p.Id AND Splitter.Id = 1
LEFT JOIN Daughters d ON d.ParentId = p.Id AND Splitter.Id = 2
WHERE p.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.

Activity

  1. roji commented on Sep 9, 2020

    @roji
    Member

    @Timovzl thanks for this proposal, we'll study this and respond soon.

  2. added this to the Backlog milestone on Sep 11, 2020
  3. roji commented on Sep 12, 2020

    @roji
    Member

    @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.

  4. roji commented on Sep 12, 2020

    @roji
    Member

    Note when investigating - do actual cross-database benchmarks to measure and compare perf.

  5. Timovzl commented on Sep 13, 2020

    @Timovzl
    Author

    @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.

  6. roji commented on Sep 13, 2020

    @roji
    Member

    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.

  7. Timovzl commented on Sep 14, 2020

    @Timovzl
    Author

    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). :)

  8. roji commented on Sep 14, 2020

    @roji
    Member

    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.

  9. 8 remaining items

  10. Emill commented on Mar 1, 2021

    @Emill

    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

    SELECT
    parent.id AS parent_id,
    parent.col1 AS parent_col1,
    son.id AS son_id,
    son.col1 AS son_col1,
    daughter.id AS daughter_id,
    daughter.col1 AS daughter_col1
    FROM parent
    LEFT JOIN son ON parent.id = son.parent_id
    LEFT JOIN daughter ON parent.id = daughter.parent_id
    ORDER BY parent.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.id AS parent_id,
        parent.col1 AS parent_col1,
        son.id AS son_id,
        son.col1 AS son_col1,
        NULL AS daughter_id,
        NULL AS daughter_col1
        FROM parent LEFT JOIN son ON parent.id = son.parent_id)
      UNION ALL
        (SELECT 2 AS c1
        parent.id AS parent_id,
        parent.col1 AS parent_col1,
        NULL AS son_id,
        NULL AS son_col1,
        daughter.id AS daughter_id,
        daughter.col1 AS daughter_col1,
        FROM parent INNER JOIN daughter ON parent.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).

  11. Emill commented on Mar 10, 2021

    @Emill

    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:

    SELECT p.Id, Splitter.Id, p2.*, s.*, d.*
    FROM Parents p
    INNER JOIN (SELECT 0 AS Id UNION ALL SELECT 1 UNION ALL SELECT 2) AS Splitter ON TRUE
    LEFT JOIN LATERAL (SELECT p.*) p2 ON Splitter.Id = 0
    LEFT JOIN Sons s ON s.ParentId = p.Id AND Splitter.Id = 1
    LEFT JOIN Daughters d ON d.ParentId = p.Id AND Splitter.Id = 2
    ORDER BY p.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.

  12. Emill commented on Mar 14, 2021

    @Emill

    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 t1
    LEFT JOIN
    (SELECT * FROM ...) t2
    ORDER BY t1.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.

  13. added theissue type on Jun 15, 2025
  14. bachratyg commented on Jul 16, 2025

    @bachratyg

    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:

    SELECT 1 AS SplitterId, <..vals from split query A>, <..null from split query B>, <..null from split query C> FROM (<split query A>)
    UNION ALL
    SELECT 2 AS SplitterId, <..null from split query A>, <..vals from split query B>, <..null from split query C> FROM (<split query B>)
    UNION ALL
    SELECT 3 AS SplitterId, <..null from split query A>, <..null from 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
    (
        SELECT 1, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS rn, * FROM (<split query A>) 
    ) a
    FULL JOIN
    (
        SELECT 2, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS rn, * FROM (<split query B>) 
    ) b ON a.rn=b.rn
    FULL JOIN
    (
        SELECT 3, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) 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?

  15. roji commented on Jul 17, 2025

    @roji
    Member

    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.

  16. davidroth commented on Jul 17, 2025

    @davidroth
    Contributor

    @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

  17. bachratyg commented on Jul 18, 2025

    @bachratyg

    Transferring nulls is generally pretty efficient, but of course we'd need to confirm.

    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.

  18. bachratyg commented on Jul 18, 2025

    @bachratyg

    @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

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions