Re: should we have a fast-path planning for OLTP starjoins?

Поиск
Список
Период
Сортировка
Искать

Re: should we have a fast-path planning for OLTP starjoins?

От:
Nico Williams <nico@cryptonector.com>
Дата:
On Tue, Feb 04, 2025 at 03:00:49PM +0100, Tomas Vondra wrote:

I'm late to this party.  I have apps that do start queries like this a
lot.  These apps fall into this type:

> Or maybe the fact table is "users" and the dimensions have all kinds of
> info about the user (address, primary e-mail address, balance, ...).

In my case the schema is an EAV schema, but essentially it stores users,
groups, and many other such things -- the sorts you expect to find in a
directory service.

Some unsolicited advice:

 - the table source with the longest index key prefix (or full key)
   determined by WHERE clause terms is the table that should lead the
   query plan

   This is really important for the case where the query is a VIEW and
   the WHERE clause terms can get pushed into it, then:

   SELECT ...
   FROM t0
   JOIN t1 ON ...
   JOIN t2 ON ...
   ..
   JOIN tN ON ...
   -- tX's PK is (a, b, c), or maybe (a, b, c, d), but (a, b, c) is a
   -- very selective prefix of that PK index, so the query plan should
   -- start with tX
   WHERE tX.a = ... AND tX.b = ... AND tX.c = ...

 - if there is no such table source then we're asking for "all the
   data", and we might as well start with a full table scan of some
   table source, but, which?  my answer: the lexically first one in the
   query!  (why?  because it gives the query author the power to pick
   which table goes first in this case)

   SELECT ...
   FROM t0
   JOIN ...
   ...; -- no WHERE clause or no terms that provide values for prefixes
        -- of indices that we could use to find a good choice of
        -- starting table, so start with t0

> Anyway, this pattern is quite common, yet it performs quite poorly.

Yes.

> But for starjoins, a lot of this is not really needed. In the simplest
> case (no conditions on dimensions etc) it does not really matter in what
> order we join those, and filters on dimensions make it only a little bit

But here you can just use the order that the SQL uses.  It gives the
author some power.

> more complicated (join the most selective first).

Yes.

> So I've been wondering how difficult would it be to have a special
> fast-path mode for starjoins, completely skipping most of this. I
> cobbled together a WIP/PoC patch (attached) on the way from FOSDEM, and
> it seems to help quite a bit.

Yay!  _Thank you_!

> So that about triples the throughput. If you bump join_collapse_limit to
> 12, it gets even clearer
> 
>      build              1            16
>   --------------------------------------
>     master            200          2000
>    patched           4500         48000
> 
> That's a 20x improvement - not bad. Sure, this is on a tiny dataset, and
> with larger data sets it might need to do I/O, diminishing the benefits.
> It's just an example to demonstrate the benefits.

Fantastic!  I can't wait to use this in prod.

> But the bigger question is whether it makes sense to have such fast-path
> modes for certain query shapes. The patch "hard-codes" the planning for
> starjoin queries, but we clearly can't do that for every possible join
> shape (because then why have dynamic join search at all?).

IMO: Yes for starjoins.  The reason is:

> I do think starjoins might be sufficiently unique / special to justify
> this, but maybe it would be possible to instead improve the regular join
> order search to handle this case better? I don't have a very clear idea
> what would that look like, though :-(

If you're not pessimizing other cases and you're getting a 4x to 20x
improvement then the uniqueness of the starjoin case and the frequent
use of starjoin queries makes this fast-path worthwhile.

Moreover, I think in general if you can cheaply determine a "kind" of
query and then apply query plan searches / optimizations that are most
relevant to the query's "kind" then I think that's a good way to unlock
more useful optimizations.

> I did check what do some other databases do, and they often have some
> sort of "hint" to nudge the let the optimizer know this is a starjoin.

I don't think a hint is needed here.

BTW, I like hints, but only out-of-band, not embedded in the SQL.
Unfortunately out-of-band hinting is not really viable because to
introduce it one would need new APIs (and possibly protocol work).

Nico
-- 


Re: should we have a fast-path planning for OLTP starjoins?

От:
Tom Lane <tgl@sss.pgh.pa.us>
Дата:
Nico Williams  writes:
> Some unsolicited advice:
> ...
> But here you can just use the order that the SQL uses.  It gives the
> author some power.

If that's the approach you want, it's been possible for decades:
"set join_collapse_limit = 1" and away you go.  I don't feel a
need to invent a different version of that for star schemas.

I do not think this patch should have ambitions beyond the stated
one of avoiding useless join-order search effort.  If you try to
load more than that onto the plate you'll probably end in failure.

			regards, tom lane


Re: should we have a fast-path planning for OLTP starjoins?

От:
Tomas Vondra <tomas@vondra.me>
Дата:
On 11/15/25 16:57, Tom Lane wrote:
> Nico Williams  writes:
>> Some unsolicited advice:
>> ...
>> But here you can just use the order that the SQL uses.  It gives the
>> author some power.
> 
> If that's the approach you want, it's been possible for decades:
> "set join_collapse_limit = 1" and away you go.  I don't feel a
> need to invent a different version of that for star schemas.
> 
> I do not think this patch should have ambitions beyond the stated
> one of avoiding useless join-order search effort.  If you try to
> load more than that onto the plate you'll probably end in failure.
> 

FWIW I certainly agree with this. The motivation is to speed up planning
with starjoin-like queries, and that's still the primary goal. If it
could handle more complex cases (snowflake, inverse starjoin), great.
But I have no ambition to make it somehow generic and much more complex.

The main thing I'm really unsure about is what to do about joins that
increase the cardinality. AFAICS that's the only possible regression if
we simply move joins with dimensions at the end. Not sure what to do
about that before the actual join search ...

regards

-- 
Tomas Vondra



Re: should we have a fast-path planning for OLTP starjoins?

От:
Tom Lane <tgl@sss.pgh.pa.us>
Дата:
I spent a little time staring at the v5 patches.  Obviously there
are a bunch of minor details to be verified, which you've carefully
provided XXX comments about, and I didn't really go through those
yet.  There are two big-picture questions that are bothering me:

1. I do not think I believe the premise that the dimension tables
typically won't have restriction clauses.  ISTM that a typical
query might be like

      select sum(o.total_price) from
	orders o
	join customers c on c.id = o.c_id
	join products p on p.id = o.p_id
	where c.customer_name = 'Wile E Coyote'
	and p.product_name = 'Rocket Skates';

The only reason to join a dimension table that lacks a restriction
clause is if you need some of its fields in the output, which you
might but I'm not sure that's such a common case.  (Have you got
evidence to the contrary?)  So I feel like we're not going to be
getting all that much win if we are not willing to treat such tables
as dimension tables.  We could do something simplistic like order
those dimensions by the selectivity of their baserestrict clauses,
joining the most-restricted ones first and any restriction-free ones
last.

2. I'm pretty un-excited about the 0002 patch altogether.  I'm having
a hard time visualizing cases where it helps, other than left joins
to dimension tables which I don't really think are common either.
I did a bit of poking around on the net and found that it seems to
be common to restrict star-join optimizations to equijoins (e.g.
SAP says explicitly that they only handle that case).  I think we'd
be better off to focus on the allow-baserestrict-clauses extension
than the allow-join-order-restrictions extension.

			regards, tom lane


Re: should we have a fast-path planning for OLTP starjoins?

От:
Bruce Momjian <bruce@momjian.us>
Дата:
On Fri, Nov 21, 2025 at 03:14:15PM -0500, Tom Lane wrote:
> I spent a little time staring at the v5 patches.  Obviously there
> are a bunch of minor details to be verified, which you've carefully
> provided XXX comments about, and I didn't really go through those
> yet.  There are two big-picture questions that are bothering me:
> 
> 1. I do not think I believe the premise that the dimension tables
> typically won't have restriction clauses.  ISTM that a typical
> query might be like
> 
>       select sum(o.total_price) from
> 	orders o
> 	join customers c on c.id = o.c_id
> 	join products p on p.id = o.p_id
> 	where c.customer_name = 'Wile E Coyote'
> 	and p.product_name = 'Rocket Skates';

Yes, I am sure it is typical because I have seen cartoons use exactly
those products.  ;-)

> The only reason to join a dimension table that lacks a restriction
> clause is if you need some of its fields in the output, which you
> might but I'm not sure that's such a common case.  (Have you got
> evidence to the contrary?)  So I feel like we're not going to be
> getting all that much win if we are not willing to treat such tables
> as dimension tables.  We could do something simplistic like order
> those dimensions by the selectivity of their baserestrict clauses,
> joining the most-restricted ones first and any restriction-free ones
> last.

Oh, I thought the patch already did this, e.g., the patch was going to
make groups, e.g., foreign keys with restrictions, foreign keys without
restrictions, and no foreign key (might add rows).  The first group was
going to be sorted by their selectivity, and the last group was going to
be sorted by how much they add rows, if that is possible.

-- 
  Bruce Momjian          https://momjian.us
  EDB                                      https://enterprisedb.com

  Do not let urgent matters crowd out time for investment in the future.


Re: should we have a fast-path planning for OLTP starjoins?

От:
Tomas Vondra <tomas@vondra.me>
Дата:


On 11/21/25 21:14, Tom Lane wrote:
> I spent a little time staring at the v5 patches.  Obviously there
> are a bunch of minor details to be verified, which you've carefully
> provided XXX comments about, and I didn't really go through those
> yet.  There are two big-picture questions that are bothering me:
> 
> 1. I do not think I believe the premise that the dimension tables
> typically won't have restriction clauses.  ISTM that a typical
> query might be like
> 
>       select sum(o.total_price) from
> 	orders o
> 	join customers c on c.id = o.c_id
> 	join products p on p.id = o.p_id
> 	where c.customer_name = 'Wile E Coyote'
> 	and p.product_name = 'Rocket Skates';
> 
> The only reason to join a dimension table that lacks a restriction
> clause is if you need some of its fields in the output, which you
> might but I'm not sure that's such a common case.  (Have you got
> evidence to the contrary?)  So I feel like we're not going to be
> getting all that much win if we are not willing to treat such tables
> as dimension tables.  We could do something simplistic like order
> those dimensions by the selectivity of their baserestrict clauses,
> joining the most-restricted ones first and any restriction-free ones
> last.
> 

Good question. I don't have a great evidence such joins to dimensions
(without additional restrictions) are a common case. It's partially a
guess and partially based on my past experience.

I have seen a lot of such joins in analytical workloads, where the join
is followed by an aggregation, with GROUP BY referencing attributes from
the dimensions. Of course, that may be an argument against worrying
about the planning too much, because with enough data the timing is
going to be dominated by the join/aggregation execution. However, it's
surprising how little data many analytical workloads actually access, so
it's not that clear.

The other use case I've been thinking about is poorly written queries,
joining more tables than needed. A traditional example is an ORM loading
more data than needed, to load the whole "object". I don't know how
prevalent this is today - it used to be a pretty common issue, and I
doubt it improved. I think it's not that different from the self-join
removal (the tradeoffs may be different, of course). I realize we try
not to add complexity for such cases, especially if it might hurt well
written queries.

Actually, I initially investigated at the opposite example, i.e. all
dimensions joining to the fact.id, see create-2/select-2 scripts. And
then I realized starjoins have mostly the same issue. But it's true the
v5 patch does not actually help this original query.


> 2. I'm pretty un-excited about the 0002 patch altogether.  I'm having
> a hard time visualizing cases where it helps, other than left joins
> to dimension tables which I don't really think are common either.
> I did a bit of poking around on the net and found that it seems to
> be common to restrict star-join optimizations to equijoins (e.g.
> SAP says explicitly that they only handle that case).  I think we'd
> be better off to focus on the allow-baserestrict-clauses extension
> than the allow-join-order-restrictions extension.
> 

I recall seen such queries (with LEFT joins) in analytics workloads, but
it's definitely less common than inner starjoins. So I agree focusing on
allowing baserestrict clauses is probably more useful/important.


FWIW I tried searching for more info too, but all the SAP pages
suggested by google return 404 to me :-(


regards

-- 
Tomas Vondra



Re: should we have a fast-path planning for OLTP starjoins?

От:
Tomas Vondra <tomas@vondra.me>
Дата:
On 11/21/25 21:47, Bruce Momjian wrote:
> On Fri, Nov 21, 2025 at 03:14:15PM -0500, Tom Lane wrote:
>> I spent a little time staring at the v5 patches.  Obviously there
>> are a bunch of minor details to be verified, which you've carefully
>> provided XXX comments about, and I didn't really go through those
>> yet.  There are two big-picture questions that are bothering me:
>>
>> 1. I do not think I believe the premise that the dimension tables
>> typically won't have restriction clauses.  ISTM that a typical
>> query might be like
>>
>>       select sum(o.total_price) from
>> 	orders o
>> 	join customers c on c.id = o.c_id
>> 	join products p on p.id = o.p_id
>> 	where c.customer_name = 'Wile E Coyote'
>> 	and p.product_name = 'Rocket Skates';
> 
> Yes, I am sure it is typical because I have seen cartoons use exactly
> those products.  ;-)
> 

;-)

>> The only reason to join a dimension table that lacks a restriction
>> clause is if you need some of its fields in the output, which you
>> might but I'm not sure that's such a common case.  (Have you got
>> evidence to the contrary?)  So I feel like we're not going to be
>> getting all that much win if we are not willing to treat such tables
>> as dimension tables.  We could do something simplistic like order
>> those dimensions by the selectivity of their baserestrict clauses,
>> joining the most-restricted ones first and any restriction-free ones
>> last.
> 
> Oh, I thought the patch already did this, e.g., the patch was going to
> make groups, e.g., foreign keys with restrictions, foreign keys without
> restrictions, and no foreign key (might add rows).  The first group was
> going to be sorted by their selectivity, and the last group was going to
> be sorted by how much they add rows, if that is possible.
> 

No, the patch never did that. The various XXX comments discuss that as a
future optimization. Aren't the comments clear enough?

I think it'd work about the way you described, except that joins without
foreign keys can both increase and decrease the cardinality, and those
that reduce cardinality would need to be moved to the first group.

Another question is what to do about snowflake joins, as a common
extension/generalization of starjoins. I think we'd need to identify the
groups of dimensions (for the branches), and treat those as a single
logical dimension.


regards

-- 
Tomas Vondra



Re: should we have a fast-path planning for OLTP starjoins?

От:
Bruce Momjian <bruce@momjian.us>
Дата:
On Sun, Nov 23, 2025 at 03:53:17PM +0100, Tomas Vondra wrote:
> >> The only reason to join a dimension table that lacks a restriction
> >> clause is if you need some of its fields in the output, which you
> >> might but I'm not sure that's such a common case.  (Have you got
> >> evidence to the contrary?)  So I feel like we're not going to be
> >> getting all that much win if we are not willing to treat such tables
> >> as dimension tables.  We could do something simplistic like order
> >> those dimensions by the selectivity of their baserestrict clauses,
> >> joining the most-restricted ones first and any restriction-free ones
> >> last.
> > 
> > Oh, I thought the patch already did this, e.g., the patch was going to
> > make groups, e.g., foreign keys with restrictions, foreign keys without
> > restrictions, and no foreign key (might add rows).  The first group was
> > going to be sorted by their selectivity, and the last group was going to
> > be sorted by how much they add rows, if that is possible.
> > 
> 
> No, the patch never did that. The various XXX comments discuss that as a
> future optimization. Aren't the comments clear enough?

I think my brain got lost in the patch --- I was happy I got as far as I
did in understanding it.  :-)

> I think it'd work about the way you described, except that joins without
> foreign keys can both increase and decrease the cardinality, and those
> that reduce cardinality would need to be moved to the first group.

I see, makes sense.

-- 
  Bruce Momjian          https://momjian.us
  EDB                                      https://enterprisedb.com

  Do not let urgent matters crowd out time for investment in the future.


Re: should we have a fast-path planning for OLTP starjoins?

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Sun, Nov 23, 2025 at 9:39 AM Tomas Vondra  wrote:
> > 1. I do not think I believe the premise that the dimension tables
> > typically won't have restriction clauses.  ISTM that a typical
> > query might be like
> >
> >       select sum(o.total_price) from
> >       orders o
> >       join customers c on c.id = o.c_id
> >       join products p on p.id = o.p_id
> >       where c.customer_name = 'Wile E Coyote'
> >       and p.product_name = 'Rocket Skates';
> >
>
> Good question. I don't have a great evidence such joins to dimensions
> (without additional restrictions) are a common case. It's partially a
> guess and partially based on my past experience.

In my experience, restriction clauses on dimension tables are very common.

-- 
Robert Haas
EDB: http://www.enterprisedb.com


Re: should we have a fast-path planning for OLTP starjoins?

От:
Tomas Vondra <tomas@vondra.me>
Дата:
On 11/24/25 21:55, Robert Haas wrote:
> On Sun, Nov 23, 2025 at 9:39 AM Tomas Vondra  wrote:
>>> 1. I do not think I believe the premise that the dimension tables
>>> typically won't have restriction clauses.  ISTM that a typical
>>> query might be like
>>>
>>>       select sum(o.total_price) from
>>>       orders o
>>>       join customers c on c.id = o.c_id
>>>       join products p on p.id = o.p_id
>>>       where c.customer_name = 'Wile E Coyote'
>>>       and p.product_name = 'Rocket Skates';
>>>
>>
>> Good question. I don't have a great evidence such joins to dimensions
>> (without additional restrictions) are a common case. It's partially a
>> guess and partially based on my past experience.
> 
> In my experience, restriction clauses on dimension tables are very common.
> 

Sure, but does that imply the inverse case (dimensions without non-join
restrictions) are not? I'm not sure.


regards

-- 
Tomas Vondra



Re: should we have a fast-path planning for OLTP starjoins?

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Wed, Nov 26, 2025 at 1:30 PM Tomas Vondra  wrote:
> > In my experience, restriction clauses on dimension tables are very common.
>
> Sure, but does that imply the inverse case (dimensions without non-join
> restrictions) are not? I'm not sure.

Obviously that depends on a lot of things, and I don't completely
understand what the patch does and doesn't do. But, I think it would
be sad to implement an optimization that falls over catastrophically
when such restriction clauses are present. For example, a long time
ago, I used to build web applications. Twenty, even thirty table joins
were common. There certainly wouldn't be a restriction clause on every
dimension table, but it would be an unusual situation if there were NO
restriction clauses on ANY dimension table. It's maybe also worth
mentioning that in those applications, it wasn't always a pure star
join: one central fact table would join to a bunch of codes tables,
but also very often to some other fact tables that had their own codes
tables. Point being that optimizations like this can be shown to have
a LOT of value in individual test cases even if the circumstances in
which they can be applied are very restricted, but lifting some of
those restrictions can enormously expand the number of real-world
cases to which they apply. My intuition is that a smaller gain on a
larger class of queries will win us more praise than the reverse.

-- 
Robert Haas
EDB: http://www.enterprisedb.com


Re: should we have a fast-path planning for OLTP starjoins?

От:
Tomas Vondra <tomas@vondra.me>
Дата:
On 11/28/25 19:57, Robert Haas wrote:
> On Wed, Nov 26, 2025 at 1:30 PM Tomas Vondra  wrote:
>>> In my experience, restriction clauses on dimension tables are very common.
>>
>> Sure, but does that imply the inverse case (dimensions without non-join
>> restrictions) are not? I'm not sure.
> 
> Obviously that depends on a lot of things, and I don't completely
> understand what the patch does and doesn't do. But, I think it would
> be sad to implement an optimization that falls over catastrophically
> when such restriction clauses are present. For example, a long time
> ago, I used to build web applications. Twenty, even thirty table joins
> were common. There certainly wouldn't be a restriction clause on every
> dimension table, but it would be an unusual situation if there were NO
> restriction clauses on ANY dimension table.

I think it depends on what you mean by "falls over catastrophically".

The patch identifies dimensions without restrictions, moves them aside,
and does regular join search on the rest of the relations (some of which
may be dimensions with restrictions).

So the presence of dimensions with restrictions does not disable the
optimization entirely, it just means the dimensions with restrictions
won't benefit from it. So in the worst case, it'll perform just like
before (assuming the optimization is kept cheap enough).

I'd love if the optimization worked for all dimensions, even for those
with restrictions. But I don't know about such optimization.

> It's maybe also worth
> mentioning that in those applications, it wasn't always a pure star
> join: one central fact table would join to a bunch of codes tables,
> but also very often to some other fact tables that had their own codes
> tables. 
> 

I certainly don't claim this optimization works for all queries, but
it's also not restricted to "pure" starjoins. It simply finds which
relations can be considered dimensions (i.e. joined through a FK). It
does not match the whole plan shape, or anything like that.

Yes, that may reduce the possible benefit of this optimization, because
the patch works within the "groups" generated by join_collapse_limit (so
within 8 relations by default). If those groups have few dimensions, the
patch may not help all that much.

> Point being that optimizations like this can be shown to have
> a LOT of value in individual test cases even if the circumstances in
> which they can be applied are very restricted, but lifting some of
> those restrictions can enormously expand the number of real-world
> cases to which they apply. My intuition is that a smaller gain on a
> larger class of queries will win us more praise than the reverse.

I don't disagree, but isn't this mostly what we're discussing now? I'm
trying to figure out if enough queries would benefit from this
optimization, which only applies to dimensions without restrictions.


regards

-- 
Tomas Vondra



Re: should we have a fast-path planning for OLTP starjoins?

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Fri, Nov 28, 2025 at 2:21 PM Tomas Vondra  wrote:=
> The patch identifies dimensions without restrictions, moves them aside,
> and does regular join search on the rest of the relations (some of which
> may be dimensions with restrictions).
>
> So the presence of dimensions with restrictions does not disable the
> optimization entirely, it just means the dimensions with restrictions
> won't benefit from it. So in the worst case, it'll perform just like
> before (assuming the optimization is kept cheap enough).

I'm guessing that the reason you're limiting this to relations without
restrictions is so that you don't have to reason about the join
causing cardinality changes. But I don't quite understand how you
avoid having that problem anyway. For example, suppose that we have a
fact table F which is joined to relations S1, S2, D1, D2, I1, and I2.
The joins to S1 and S2 are joins on FKs to unconstrained dimension
tables; i.e. cardinality stays the same. The joins to D1 and D2 are
joins on FKs to constrained dimension tables, i.e. cardinality
decreases. The joins to I1 and I2 on average match more than once,
i.e. cardinality increases. The optimal join order is presumably
something like F-D1-D2-S1-S2-I1-I2, so that the number of rows flowing
through each level of the join tree is kept as small as possible, but
how do you achieve this if the joins to S1 and S2 are set aside? In
the presence of row-count-inflating joins, it's wrong to suppose that
S1 and S2 should be joined at the end.

What seems more likely to be true is that we should perform the join
to S1 and the join to S2 consecutively. It's very common in my
experience for complex reporting queries to have a bunch of joins the
results of which matter very little: each one changes the cardinality
very little or not at all, and so any ordering of those joins produces
essentially the same result, and probably it's best to do them all at
whatever point in the join sequence the cardinality of the other input
is at lowest. However, I'm not sure that even this is guaranteed. For
instance, suppose that in the above example there's no index on the
column of F that joins to S2. Could it be that the only reasonable way
to join to S2 is a merge join? If so, it might be best to start by
join F to S2 using an index scan on each, and then continue by joining
to D1, D2, S1, I1, I2 in that order.

Every time I start to think about this kind of optimization, I find
myself getting hung up on corner cases like these which are, maybe,
not all that probable, but which I think people almost certainly do
rely on the planner to get right. I don't know what to do about that.
I certainly agree with the idea that we waste a lot of energy
searching through functionally identical join orders and that we
should find a way to avoid that, but I'm a little suspicious that
avoiding regressions, or even finding out whether we've introduced
any, will prove difficult.

-- 
Robert Haas
EDB: http://www.enterprisedb.com


Re: should we have a fast-path planning for OLTP starjoins?

От:
Tomas Vondra <tomas@vondra.me>
Дата:
On 11/28/25 23:50, Robert Haas wrote:
> On Fri, Nov 28, 2025 at 2:21 PM Tomas Vondra  wrote:=
>> The patch identifies dimensions without restrictions, moves them aside,
>> and does regular join search on the rest of the relations (some of which
>> may be dimensions with restrictions).
>>
>> So the presence of dimensions with restrictions does not disable the
>> optimization entirely, it just means the dimensions with restrictions
>> won't benefit from it. So in the worst case, it'll perform just like
>> before (assuming the optimization is kept cheap enough).
> 
> I'm guessing that the reason you're limiting this to relations without
> restrictions is so that you don't have to reason about the join
> causing cardinality changes. But I don't quite understand how you
> avoid having that problem anyway. For example, suppose that we have a
> fact table F which is joined to relations S1, S2, D1, D2, I1, and I2.
> The joins to S1 and S2 are joins on FKs to unconstrained dimension
> tables; i.e. cardinality stays the same. The joins to D1 and D2 are
> joins on FKs to constrained dimension tables, i.e. cardinality
> decreases. The joins to I1 and I2 on average match more than once,
> i.e. cardinality increases. The optimal join order is presumably
> something like F-D1-D2-S1-S2-I1-I2, so that the number of rows flowing
> through each level of the join tree is kept as small as possible, but
> how do you achieve this if the joins to S1 and S2 are set aside? In
> the presence of row-count-inflating joins, it's wrong to suppose that
> S1 and S2 should be joined at the end.
> 

Yes, that's certainly possible. It was discussed at the very beginning
of this thread, and at that point there was a suggestion to keep it
simple and just push the joins to the end:

https://www.postgresql.org/message-id/1751009.1738974197@sss.pgh.pa.us

I'm not claiming that's good enough, though. Maybe we should reconsider
and it needs a better solution.

> What seems more likely to be true is that we should perform the join
> to S1 and the join to S2 consecutively. It's very common in my
> experience for complex reporting queries to have a bunch of joins the
> results of which matter very little: each one changes the cardinality
> very little or not at all, and so any ordering of those joins produces
> essentially the same result, and probably it's best to do them all at
> whatever point in the join sequence the cardinality of the other input
> is at lowest. However, I'm not sure that even this is guaranteed. For
> instance, suppose that in the above example there's no index on the
> column of F that joins to S2. Could it be that the only reasonable way
> to join to S2 is a merge join? If so, it might be best to start by
> join F to S2 using an index scan on each, and then continue by joining
> to D1, D2, S1, I1, I2 in that order.
> 

Good points.

The first part reminds me the approach I mentioned a couple messages
back, We might preprocess the join lists, but instead of "removing the
dimensions" from the search, we'd group them together, and treat each
group as a single item in join_search_one_level. Then, whenever
join_search_one_level hits the group, it'd expand it into a sequence of
joins. I have not tried that yet, but it seems doable ...

However, I'm not sure about your second point - what if the join order
matters after all, e.g. because some join order can leverage ordering
(pathkeys) of the inputs, or produces ordering better for the later joins?

> Every time I start to think about this kind of optimization, I find
> myself getting hung up on corner cases like these which are, maybe,
> not all that probable, but which I think people almost certainly do
> rely on the planner to get right. I don't know what to do about that.
> I certainly agree with the idea that we waste a lot of energy
> searching through functionally identical join orders and that we
> should find a way to avoid that, but I'm a little suspicious that
> avoiding regressions, or even finding out whether we've introduced
> any, will prove difficult.
> 

True. I started working on this with two assumptions: (a) we can detect
cases when this is guaranteed to be the optimal join order, and (b) it
would be cheap to do so. Maybe one of those assumptions is not correct.


thanks

-- 
Tomas Vondra



Re: should we have a fast-path planning for OLTP starjoins?

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Fri, Nov 28, 2025 at 6:34 PM Tomas Vondra  wrote:
> True. I started working on this with two assumptions: (a) we can detect
> cases when this is guaranteed to be the optimal join order, and (b) it
> would be cheap to do so. Maybe one of those assumptions is not correct.

Probably needs testing, at least.

I wonder if there's any way that we could rule out the presence of
row-count-inflating joins, or at least identify the joins that are
definitely not row-count-inflating. I have a general feeling that we
postpone some of the estimation work that the planner does for too
long, and that moving some of it earlier would allow better
decision-making. It's very common for a query to involve a driving
table and then a bunch of joins to side tables that are all
essentially independent of each other. That is, each of those joins
will multiply the row count from the other side of the join by a
constant that does not depend very much on the join order. I don't
really know exactly what we could do that would enable us to notice
that pattern and do something about it, but it feels like we're
duplicating a lot of work

For instance, consider a 4-way join between A, B, C, and D, where A is
connected to the other three tables by join clauses, and those are the
only join clauses. Let's say that the join to B is going to multiply
the row count by 2, the join to C is going to multiply it by 1 (i.e.
no change), and the join to D is going to multiply it by 0.1 (i.e.
eliminate 90% of rows). Well, we're going to consider the A-B join and
discover that it has 2 times the cardinality of A, and then later
we'll consider the (A-C)-B join and discover that it has 2 times the
cardinality of A-C, and then later we'll consider the (A-D)-B join and
discover that it has two times the cardinality of A-D, and then later
we'll consider the (A-B-C)-D join and discover that it has two times
the cardinality of A-B-C. As the number of tables grows, the number of
times we rediscover the effect of joining to a certain table grows, I
believe, exponentially.

Of course, in theory, there's no reason why the idea that any
particular join multiplies the row count by a constant that is
independent of the join order has to be correct. For instance, if the
A-B join multiplies the same rows that the A-D join eliminates, then
you can't set a fixed multiplier for either one. But in practice, even
when that's the case, we're not aware of it: when evaluating a join
column from, say, the output of the A-B join, we use the statistics
for the underlying column of A or B, without any modification
reflecting what the A-B join did to the distribution. So I think that
our estimates will behave like join-order-independent multipliers even
when the reality is otherwise. I'm not at all sure that I'm totally
right about this, and I sort of expect you or Tom to point out why I'm
totally weak in the head for thinking that it's the case, but I feel
like there might be the kernel of an idea here even if the details are
wrong.

Because, like, I think the general complexity of determining the
optimal join order is known to be some horrifically non-polynomial
time thing, but there are lots of real-world problems where I think a
human being would try to do it in linear time, by initially choosing
the driving table, and then what to join to first, second, third, etc.
And I think that's the kind of case that you're trying to pursue with
this optimization, so it feels intuitively logical that something
should be possible. That said, I don't know whether from a theoretical
perspective it really is possible to do something like this in a
reliable way, making it a pure optimization, or whether you would be
doomed to always get some cases wrong, making it more like an optional
planner mode or something. Either way, I can't shake the feeling that
determining essentially every important fact about every join only
when we perform the main join search makes it a lot harder to imagine
ever avoiding the main join search.

-- 
Robert Haas
EDB: http://www.enterprisedb.com


Re: should we have a fast-path planning for OLTP starjoins?

От:
Bruce Momjian <bruce@momjian.us>
Дата:
On Fri, Nov 28, 2025 at 05:50:34PM -0500, Robert Haas wrote:
> I'm guessing that the reason you're limiting this to relations without
> restrictions is so that you don't have to reason about the join
> causing cardinality changes. But I don't quite understand how you
> avoid having that problem anyway. For example, suppose that we have a
> fact table F which is joined to relations S1, S2, D1, D2, I1, and I2.
> The joins to S1 and S2 are joins on FKs to unconstrained dimension
> tables; i.e. cardinality stays the same. The joins to D1 and D2 are
> joins on FKs to constrained dimension tables, i.e. cardinality
> decreases. The joins to I1 and I2 on average match more than once,
> i.e. cardinality increases. The optimal join order is presumably
> something like F-D1-D2-S1-S2-I1-I2, so that the number of rows flowing
> through each level of the join tree is kept as small as possible, but
> how do you achieve this if the joins to S1 and S2 are set aside? In
> the presence of row-count-inflating joins, it's wrong to suppose that
> S1 and S2 should be joined at the end.

I spend some time thinking about this email.  I have a few questions. 
As I see it, we are regrouping joins of a single table into three
groups:

1.  restriction joins
2.  neutral joins
3.  expansion joins

It seems we have to identify these joins _before_ we actually start the
main optimizer.  We can identify restriction joins since we see the
restriction in the query, and we can identify neutral joins because of
foreign keys.  How do we identify expansion joins?  Is it all the joins
which are not the previous types?

> What seems more likely to be true is that we should perform the join
> to S1 and the join to S2 consecutively. It's very common in my
> experience for complex reporting queries to have a bunch of joins the
> results of which matter very little: each one changes the cardinality
> very little or not at all, and so any ordering of those joins produces
> essentially the same result, and probably it's best to do them all at
> whatever point in the join sequence the cardinality of the other input
> is at lowest. However, I'm not sure that even this is guaranteed. For
> instance, suppose that in the above example there's no index on the
> column of F that joins to S2. Could it be that the only reasonable way
> to join to S2 is a merge join? If so, it might be best to start by
> join F to S2 using an index scan on each, and then continue by joining
> to D1, D2, S1, I1, I2 in that order.

So, this got me thinking.  As the optimizer runs, it doesn't choose just
the cheapest path for each stage, but retains paths with higher costs if
they have sort orders (pathkeys) that might be useful in later stages.

In the group execution order we are considering:

1.  restriction joins
2.  neutral joins
3.  expansion joins

do we generate only the cheapest path for each group or return multiple
paths that can be considered by later group executions?  If not, if we
join the same column in stages 1 & 2, would it make sense to move the
stage 2 join into stage 1 so we can potentially use sort order
(pathkeys) for both joins?  Similarly if we join the same column in
stage 2 & 3 can we move the stage 2 join to stage 3?  I don't think it
is worth moving stage 1 to 3 or 3 to 1 since it seems too risky.

I am sorry if this was already discussed in the patch comments.

What Robert is saying in the above paragraph is even more complex ---
that we might want to use an index on the fact table for a merge join of
a stage 2 or 3 join, and then do the other joins.  How would we detect
this?  Could we run each join on its own and see which ones choose merge
join, and move them to stage 1?

-- 
  Bruce Momjian          https://momjian.us
  EDB                                      https://enterprisedb.com

  Do not let urgent matters crowd out time for investment in the future.


Re: should we have a fast-path planning for OLTP starjoins?

От:
Bruce Momjian <bruce@momjian.us>
Дата:
On Sat, Dec 20, 2025 at 05:49:24PM -0500, Bruce Momjian wrote:
> What Robert is saying in the above paragraph is even more complex ---
> that we might want to use an index on the fact table for a merge join of
> a stage 2 or 3 join, and then do the other joins.  How would we detect
> this?  Could we run each join on its own and see which ones choose merge
> join, and move them to stage 1?

Thinking some more, how likely would we do a merge join before applying
a restrictive join?

-- 
  Bruce Momjian          https://momjian.us
  EDB                                      https://enterprisedb.com

  Do not let urgent matters crowd out time for investment in the future.


Re: should we have a fast-path planning for OLTP starjoins?

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Sat, Dec 20, 2025 at 5:49 PM Bruce Momjian  wrote:
> It seems we have to identify these joins _before_ we actually start the
> main optimizer.  We can identify restriction joins since we see the
> restriction in the query, and we can identify neutral joins because of
> foreign keys.  How do we identify expansion joins?  Is it all the joins
> which are not the previous types?

We unfortunately have no way to identify these joins before we
actually start the main optimizer; that's not how the code works. I'm
not sure if there's a reasonable way to do better, because whether the
join inflates or reduces the row count can't be known independently of
the join order in general, even though in practice it often can.

> In the group execution order we are considering:
>
> 1.  restriction joins
> 2.  neutral joins
> 3.  expansion joins
>
> do we generate only the cheapest path for each group or return multiple
> paths that can be considered by later group executions?  If not, if we
> join the same column in stages 1 & 2, would it make sense to move the
> stage 2 join into stage 1 so we can potentially use sort order
> (pathkeys) for both joins?  Similarly if we join the same column in
> stage 2 & 3 can we move the stage 2 join to stage 3?  I don't think it
> is worth moving stage 1 to 3 or 3 to 1 since it seems too risky.

I'm not sure this is what the patch is actually doing -- it's
definitely not what the current code is doing.

-- 
Robert Haas
EDB: http://www.enterprisedb.com


Re: should we have a fast-path planning for OLTP starjoins?

От:
Bruce Momjian <bruce@momjian.us>
Дата:
On Wed, Dec 24, 2025 at 08:32:42AM -0500, Robert Haas wrote:
> On Sat, Dec 20, 2025 at 5:49 PM Bruce Momjian  wrote:
> > It seems we have to identify these joins _before_ we actually start the
> > main optimizer.  We can identify restriction joins since we see the
> > restriction in the query, and we can identify neutral joins because of
> > foreign keys.  How do we identify expansion joins?  Is it all the joins
> > which are not the previous types?
> 
> We unfortunately have no way to identify these joins before we
> actually start the main optimizer; that's not how the code works. I'm
> not sure if there's a reasonable way to do better, because whether the
> join inflates or reduces the row count can't be known independently of
> the join order in general, even though in practice it often can.

Okay, makes sense.  Are we moving forward with this patch, or are we
considering the greedy join search algorithm as a possible better
solution to this problem?

	https://www.postgresql.org/message-id/flat/3FF63E99-AB4F-41A9-BC78-AAB28823FBD0%40Outlook.com

> > In the group execution order we are considering:
> >
> > 1.  restriction joins
> > 2.  neutral joins
> > 3.  expansion joins
> >
> > do we generate only the cheapest path for each group or return multiple
> > paths that can be considered by later group executions?  If not, if we
> > join the same column in stages 1 & 2, would it make sense to move the
> > stage 2 join into stage 1 so we can potentially use sort order
> > (pathkeys) for both joins?  Similarly if we join the same column in
> > stage 2 & 3 can we move the stage 2 join to stage 3?  I don't think it
> > is worth moving stage 1 to 3 or 3 to 1 since it seems too risky.
> 
> I'm not sure this is what the patch is actually doing -- it's
> definitely not what the current code is doing.

I think we have general consensus that short-circuiting queries that do
many joins to a single table, like star joins, is a valid optimization. 
I guess we have to continue considering the best solution.

-- 
  Bruce Momjian          https://momjian.us
  EDB                                      https://enterprisedb.com

  Do not let urgent matters crowd out time for investment in the future.


Re: should we have a fast-path planning for OLTP starjoins?

От:
Tom Lane <tgl@sss.pgh.pa.us>
Дата:
Robert Haas  writes:
> On Sat, Dec 20, 2025 at 5:49 PM Bruce Momjian  wrote:
>> It seems we have to identify these joins _before_ we actually start the
>> main optimizer.  We can identify restriction joins since we see the
>> restriction in the query, and we can identify neutral joins because of
>> foreign keys.  How do we identify expansion joins?  Is it all the joins
>> which are not the previous types?

> We unfortunately have no way to identify these joins before we
> actually start the main optimizer; that's not how the code works. I'm
> not sure if there's a reasonable way to do better, because whether the
> join inflates or reduces the row count can't be known independently of
> the join order in general, even though in practice it often can.

I think the core idea of this proposal is to improve cases where
we *can* know that; where we can't, just do what we've always done.
Not handling every case isn't a fatal objection, as long as the
patch doesn't spend much time to discover that it can't help.

Having said that, I'm starting to wonder whether "do this stuff in a
separate pass before the main optimizer" is the wrong structural
decision.  Should we be injecting the logic at some later point
where we've gathered more information?  At least in principle,
we should be able to build all base-relation Paths before we start
to think about join order; would having those help?

			regards, tom lane


Re: should we have a fast-path planning for OLTP starjoins?

От:
Tomas Vondra <tomas@vondra.me>
Дата:


On 12/24/25 19:16, Tom Lane wrote:
> Robert Haas  writes:
>> On Sat, Dec 20, 2025 at 5:49 PM Bruce Momjian  wrote:
>>> It seems we have to identify these joins _before_ we actually start the
>>> main optimizer.  We can identify restriction joins since we see the
>>> restriction in the query, and we can identify neutral joins because of
>>> foreign keys.  How do we identify expansion joins?  Is it all the joins
>>> which are not the previous types?
> 
>> We unfortunately have no way to identify these joins before we
>> actually start the main optimizer; that's not how the code works. I'm
>> not sure if there's a reasonable way to do better, because whether the
>> join inflates or reduces the row count can't be known independently of
>> the join order in general, even though in practice it often can.
> 
> I think the core idea of this proposal is to improve cases where
> we *can* know that; where we can't, just do what we've always done.
> Not handling every case isn't a fatal objection, as long as the
> patch doesn't spend much time to discover that it can't help.
> 

Right. This was conceived as a cheap opportunistic optimization. It has
to be cheap enough to not hurt queries that don't benefit it (which may
be most queries).

> Having said that, I'm starting to wonder whether "do this stuff in a
> separate pass before the main optimizer" is the wrong structural
> decision.  Should we be injecting the logic at some later point
> where we've gathered more information?  At least in principle,
> we should be able to build all base-relation Paths before we start
> to think about join order; would having those help?
> 

It's entirely possible doing it in a separate pass before the "regular"
join order search is the wrong approach. But if wanted to do that later,
when would that be?

I don't think doing that after building baserels would be enough. What
additional information would that give us? AFAICS we already have
RelOptInfos for baserels with all the necessary info about foreign keys,
join clauses etc. The thing we don't have is RelOptInfos for the joins,
which means we can't use join_is_legal() etc.

An idea I floated some time back is "grouping" the dimension joins into
a single "group entry", and teach join_search_one_level() to expand it
into a sequence of joins whenever it hits it. It'd still consider all
join orders of the "other" joins (some of which may increase or decrease
the join cardinality).

Would this be a better structure? It'd be later than what we do now, and
we can't really do it any later, I think.


regards

-- 
Tomas Vondra



Re: should we have a fast-path planning for OLTP starjoins?

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Wed, Dec 24, 2025 at 1:16 PM Tom Lane  wrote:
> Having said that, I'm starting to wonder whether "do this stuff in a
> separate pass before the main optimizer" is the wrong structural
> decision.  Should we be injecting the logic at some later point
> where we've gathered more information?  At least in principle,
> we should be able to build all base-relation Paths before we start
> to think about join order; would having those help?

I've been wondering for a while about making cardinality estimation a
separate pass from path construction. One reason is that we currently
come up with different row count estimates for partitionwise and
non-partitionwise paths for the same rel, which doesn't really make
sense. We could do partitionwise estimates for joins that could be
done partitionwise even if partitionwise join is not selected or even
if it is entirely disabled, and I think we'd get more accurate
estimates (as we should for baserels also). But I wonder if it might
help with this problem, too. Like, suppose we try to construct a
star-join path using some fast-path, and as we go we compute
cardinality estimates for the joinrels we consider building. At any
point, we can decide to give up, e.g. because we find a row-count
inflating join, or something that otherwise doesn't meet the criteria
for the fast path. At that point, we can fall back and do the standard
join search, and all the cardinality estimates we used are still
available and don't need to be recomputed, so the only effort we've
wasted is the effort of constructing paths for some rels. Those paths
probably do need to be discarded, unless our fast-path always computes
the full path set for each rel it considers. But being able to reuse
the cardinality estimates would limit the wasted work.

Your idea of building base-relation paths early, thus also getting
base-relation cardinality estimates, has some of the same advantages
and might be easier to implement. It would mean that we lose any join
cardinality estimates that the fast-path algorithm computes, so I
think it's probably at least modestly worse if you ignore
implementation complexity, but I can almost hear you telling me that
we cannot and should not ignore implementation complexity, which is
fair enough as far as it goes.

-- 
Robert Haas
EDB: http://www.enterprisedb.com


Re: should we have a fast-path planning for OLTP starjoins?

От:
Tomas Vondra <tomas@vondra.me>
Дата:
Вложения:
Hi,

I got into a couple discussions regarding this patch in Vancouver last week.

Some of the questions were about possible overlap with the "foreign key
joins" patch Joel is working on. That patch needs to prove some of the
same questions about joins (e.g. which joins can't change cardinality).
So it seems plausible some this join planning patch could leverage some
of the information eventually introduced by that patch, and maybe apply
the optimization in more cases. Not sure.

But re-reading the old thread, this doesn't seem to be why it got stuck.
We already can identify dimensions joined on foreign keys, and that
seems like a good start.

IIRC the thing that worried me was that just sticking the joins at the
end is pretty heavy-handed. It can easily end up making the plan worse,
if one of the other joins increases the cardinality. Would that be
common? Probably not, but it seems unnecessarily risky.

Ideally, we'd do join that reduce cardinality first (with the regular DP
join search), then join all the dimensions, and finally do all joins
that expand cardinality (again, using the regular DP). But the earlier
patches worked by adjusting the join tree in query_planner(), i.e. way
before we get to calculate join cardinalities.

My plan (mentioned even during the Vancouver hallway track) was to
invent a new type of jointree "entry" representing the dimensions, and
modifying the join_search_one_level() et al to "expand" it whenever we
decide to join it. So it'd get the join group, and replace it with a
sequence of joins of all the dimensions. We'd try it in various places,
and could pick the best plan. But it seemed pretty complex and invasive,
so I kept postponing the work.

I started hacking on it this week, but I also started thinking if there
might be a better solution, that would fit into the current join search
more naturally. And I think I actually found a good approach.

It works like this:

1) query_planner()

Determine if the query includes a starjoin (or multiple), and remember
the relids included in the starjoin cluster. Pick a "canonical" join
order for each starjoin cluster we found (e.g. with dimensions in relid
order).

2) standard_join_search()/join_search_one_level()

When constructing the join rels (e.g. in make_join_rel or right before
it's called), check that the new rel would violate the canonical order.
If it would, refuse to create it, just like we do for various other join
restrictions.

The new join restriction is that if the join result includes a subset of
the starjoin cluster, then it has to include the fact + prefix of the
list of dimensions (which is the canonical join order).

Note: It should be possible to make the restriction even more strict, if
needed (e.g. to effectively join all dimensions at once, with no other
joins in between).


The attached patch v6 does this. It's a bit of a PoC quality, but it
should be good enough for testing and experiments (it does pass
check-world for me, but some parts still need more care / cleanup).

I also did a buch of tests to see how effective it is, and it seems
pretty effective. It gives me ~80% throughput of join_collapse_limit=1,
even with extreme number of dimensions (e.g. 16), with disabled geqo and
join_collapse_limit=16 (so it's all in one join list). The current code
drops to ~1% of join_collapse_limit=1, so this is about two orders of
magnitude faster.

Yes, this is in situations when the join does nothing during execution
(the fact table is empty). So in practice the improvement will be
smaller, but it can still be a substantial speedup, depending on how
much other work it's doing.

Attached are a couple charts from a test with 1-15 dimensions (scripts
attached too). I was wondering how geqo affects this, so I tried with
geqo=on/off, and with join_collapse_limit=1/8/16.

With join_collapse_limit=1 there's no difference between any of the runs
(master, patches with on/off). Here's an example of results:

  dims   master(1)   master  sj/off    sj/on  master   sj/off   sj/on
  -------------------------------------------------------------------
  1          49485    48797   48966    49118     99%      99%     99%
  3          26886    22003   21319    24322     82%      79%     90%
  5          17759     7923    7634    15434     45%      43%     87%
  7          13110     2122    2071    11290     16%      16%     86%
  9          10390      462     445     8709      4%       4%     84%
  11          7781       87      86     6488      1%       1%     83%
  13          5948       14      14     5749      0%       0%     97%
  15          5237        1       1     4227      0%       0%     81%

The first column is for master with join_collapse_limit=1, which I take
as the best possible throughtput, if we eliminate the join order search
almost completely. The rest is with geqo=off and join_collapse_limit=16.

So that's the 80% of possible throughput, pretty good IMO. Especially
considering master is at 1 tps.

There are a couple more interesting charts, and a CSV with raw results.
A funny (but not entirely surprising) detail is that geqo=on helps a bit
(from 1tps to ~90tps for 15 dimensions), but it's still far from the
limit=1 throughput of ~5200 tps. The fastpath join order does better.


I'm sure the code needs cleanups and fixes, but I like the approach way
more than the original plan (inventing a new group join entry).

Any comments regarding this alternative approach?


regards

-- 
Tomas Vondra

Re: should we have a fast-path planning for OLTP starjoins?

От:
Bruce Momjian <bruce@momjian.us>
Дата:
On Fri, May 29, 2026 at 12:11:32AM +0200, Tomas Vondra wrote:
> But re-reading the old thread, this doesn't seem to be why it got stuck.
> We already can identify dimensions joined on foreign keys, and that
> seems like a good start.
> 
> IIRC the thing that worried me was that just sticking the joins at the
> end is pretty heavy-handed. It can easily end up making the plan worse,
> if one of the other joins increases the cardinality. Would that be
> common? Probably not, but it seems unnecessarily risky.

Right.

> Ideally, we'd do join that reduce cardinality first (with the regular DP
> join search), then join all the dimensions, and finally do all joins
> that expand cardinality (again, using the regular DP). But the earlier
> patches worked by adjusting the join tree in query_planner(), i.e. way
> before we get to calculate join cardinalities.

Yes, I remember discussing that.

> It works like this:
> 
> 1) query_planner()
> 
> Determine if the query includes a starjoin (or multiple), and remember
> the relids included in the starjoin cluster. Pick a "canonical" join
> order for each starjoin cluster we found (e.g. with dimensions in relid
> order).
> 
> 2) standard_join_search()/join_search_one_level()
> 
> When constructing the join rels (e.g. in make_join_rel or right before
> it's called), check that the new rel would violate the canonical order.
> If it would, refuse to create it, just like we do for various other join
> restrictions.

This is how you avoid the factorial explosion of plan options, right?

> The new join restriction is that if the join result includes a subset of
> the starjoin cluster, then it has to include the fact + prefix of the
> list of dimensions (which is the canonical join order).

Sorry, I got lost here.  What is "prefix?"  I looked at the patch and
also could not understand it.

> Note: It should be possible to make the restriction even more strict, if
> needed (e.g. to effectively join all dimensions at once, with no other
> joins in between).

The patch is quite small.

> Attached are a couple charts from a test with 1-15 dimensions (scripts
> attached too). I was wondering how geqo affects this, so I tried with
> geqo=on/off, and with join_collapse_limit=1/8/16.
> 
> With join_collapse_limit=1 there's no difference between any of the runs
> (master, patches with on/off). Here's an example of results:
> 
>   dims   master(1)   master  sj/off    sj/on  master   sj/off   sj/on
>   -------------------------------------------------------------------
>   1          49485    48797   48966    49118     99%      99%     99%
>   3          26886    22003   21319    24322     82%      79%     90%
>   5          17759     7923    7634    15434     45%      43%     87%
>   7          13110     2122    2071    11290     16%      16%     86%
>   9          10390      462     445     8709      4%       4%     84%
>   11          7781       87      86     6488      1%       1%     83%
>   13          5948       14      14     5749      0%       0%     97%
>   15          5237        1       1     4227      0%       0%     81%

Impressive.

-- 
  Bruce Momjian          https://momjian.us
  EDB                                      https://enterprisedb.com

  Do not let urgent matters crowd out time for investment in the future.


Re: should we have a fast-path planning for OLTP starjoins?

От:
Tomas Vondra <tomas@vondra.me>
Дата:


On 5/30/26 20:18, Bruce Momjian wrote:
> On Fri, May 29, 2026 at 12:11:32AM +0200, Tomas Vondra wrote:
>> But re-reading the old thread, this doesn't seem to be why it got stuck.
>> We already can identify dimensions joined on foreign keys, and that
>> seems like a good start.
>>
>> IIRC the thing that worried me was that just sticking the joins at the
>> end is pretty heavy-handed. It can easily end up making the plan worse,
>> if one of the other joins increases the cardinality. Would that be
>> common? Probably not, but it seems unnecessarily risky.
> 
> Right.
> 
>> Ideally, we'd do join that reduce cardinality first (with the regular DP
>> join search), then join all the dimensions, and finally do all joins
>> that expand cardinality (again, using the regular DP). But the earlier
>> patches worked by adjusting the join tree in query_planner(), i.e. way
>> before we get to calculate join cardinalities.
> 
> Yes, I remember discussing that.
> 
>> It works like this:
>>
>> 1) query_planner()
>>
>> Determine if the query includes a starjoin (or multiple), and remember
>> the relids included in the starjoin cluster. Pick a "canonical" join
>> order for each starjoin cluster we found (e.g. with dimensions in relid
>> order).
>>
>> 2) standard_join_search()/join_search_one_level()
>>
>> When constructing the join rels (e.g. in make_join_rel or right before
>> it's called), check that the new rel would violate the canonical order.
>> If it would, refuse to create it, just like we do for various other join
>> restrictions.
> 
> This is how you avoid the factorial explosion of plan options, right?
>

Yes, exactly.

>> The new join restriction is that if the join result includes a subset of
>> the starjoin cluster, then it has to include the fact + prefix of the
>> list of dimensions (which is the canonical join order).
> 
> Sorry, I got lost here.  What is "prefix?"  I looked at the patch and
> also could not understand it.

Apologies, it may not be obvious from the code / comments (I'll try to
improve that in the next version).

Let's say we're joining "F" with dimensions D1, D2, D3. Then the
starjoins_canonicalize() finds the cluster, and picks a canonical join
order. Could be [F, D1, D2, D3] - in this order. Or whatever other
permutation of the dimensions, it's all equal.

Then starjoin_order_invalid() ensures that whatever join relation we
produce, it only even contains a prefix of this list. So a join relation
can contain [F], [F, D1], [F, D1, D2], [F, D1, D2, D3]. But it can't
contain e.g. [F, D2], because that skips the D1 - it's not a prefix.

The patch only applies this to relations from the cluster. There can be
other relations in the join "in between" the dimensions - that does not
make the join order "invalid".

So for example there may be joins to non-dimensions A and B, and we will
consider joins [F, A, D1, B, D2, D3] and so on as valid. The joins to A
and B joins can increase/decrease cardinality, but thanks to this we
should find the right place to join the dimensions.

We could even make it a bit stricter, and require that all dimensions
join "at once". I.e. after joining a dimension, only dimensions can be
joined (until all dimensions are joined). So [F, D1, A, D2] would not be
allowed. This would further reduce the number of join orders considered.

> 
>> Note: It should be possible to make the restriction even more strict, if
>> needed (e.g. to effectively join all dimensions at once, with no other
>> joins in between).
> 
> The patch is quite small.
> 
>> Attached are a couple charts from a test with 1-15 dimensions (scripts
>> attached too). I was wondering how geqo affects this, so I tried with
>> geqo=on/off, and with join_collapse_limit=1/8/16.
>>
>> With join_collapse_limit=1 there's no difference between any of the runs
>> (master, patches with on/off). Here's an example of results:
>>
>>   dims   master(1)   master  sj/off    sj/on  master   sj/off   sj/on
>>   -------------------------------------------------------------------
>>   1          49485    48797   48966    49118     99%      99%     99%
>>   3          26886    22003   21319    24322     82%      79%     90%
>>   5          17759     7923    7634    15434     45%      43%     87%
>>   7          13110     2122    2071    11290     16%      16%     86%
>>   9          10390      462     445     8709      4%       4%     84%
>>   11          7781       87      86     6488      1%       1%     83%
>>   13          5948       14      14     5749      0%       0%     97%
>>   15          5237        1       1     4227      0%       0%     81%
> 
> Impressive.
> 

Indeed. I like how it fits into the existing approach. It's a bit like
having yet another "join order restriction".


regards

-- 
Tomas Vondra



Re: should we have a fast-path planning for OLTP starjoins?

От:
Bruce Momjian <bruce@momjian.us>
Дата:
On Sat, May 30, 2026 at 08:57:20PM +0200, Tomas Vondra wrote:
> >> The new join restriction is that if the join result includes a subset of
> >> the starjoin cluster, then it has to include the fact + prefix of the
> >> list of dimensions (which is the canonical join order).
> > 
> > Sorry, I got lost here.  What is "prefix?"  I looked at the patch and
> > also could not understand it.
> 
> Apologies, it may not be obvious from the code / comments (I'll try to
> improve that in the next version).
> 
> Let's say we're joining "F" with dimensions D1, D2, D3. Then the
> starjoins_canonicalize() finds the cluster, and picks a canonical join
> order. Could be [F, D1, D2, D3] - in this order. Or whatever other
> permutation of the dimensions, it's all equal.

Uh, are D1, D2, D3 in relid order at this point?

> Then starjoin_order_invalid() ensures that whatever join relation we
> produce, it only even contains a prefix of this list. So a join relation
> can contain [F], [F, D1], [F, D1, D2], [F, D1, D2, D3]. But it can't
> contain e.g. [F, D2], because that skips the D1 - it's not a prefix.

Okay, prefix like a multi-column index prefix of columns.

> The patch only applies this to relations from the cluster. There can be
> other relations in the join "in between" the dimensions - that does not
> make the join order "invalid".
> 
> So for example there may be joins to non-dimensions A and B, and we will
> consider joins [F, A, D1, B, D2, D3] and so on as valid. The joins to A
> and B joins can increase/decrease cardinality, but thanks to this we
> should find the right place to join the dimensions.

Okay, so if D1, D2, and D3 are all "cluster" joins then aren't they are
1:1, so why would you ever put something like B between them?  If B
reduces columns, it would be before the cluster, and if it expands them
it would be after cluster.  So if B is 1:1 too, in what cases might it
be better to join B between dimension joins?

> We could even make it a bit stricter, and require that all dimensions
> join "at once". I.e. after joining a dimension, only dimensions can be
> joined (until all dimensions are joined). So [F, D1, A, D2] would not be
> allowed. This would further reduce the number of join orders considered.

Right, I guess that is what I am asking above.

> > Impressive.
> > 
> 
> Indeed. I like how it fits into the existing approach. It's a bit like
> having yet another "join order restriction".

This would be a big feature improvement for OLAP workloads.

-- 
  Bruce Momjian          https://momjian.us
  EDB                                      https://enterprisedb.com

  Do not let urgent matters crowd out time for investment in the future.


Re: should we have a fast-path planning for OLTP starjoins?

От:
Tomas Vondra <tomas@vondra.me>
Дата:
On 5/30/26 22:16, Bruce Momjian wrote:
> On Sat, May 30, 2026 at 08:57:20PM +0200, Tomas Vondra wrote:
>>>> The new join restriction is that if the join result includes a subset of
>>>> the starjoin cluster, then it has to include the fact + prefix of the
>>>> list of dimensions (which is the canonical join order).
>>>
>>> Sorry, I got lost here.  What is "prefix?"  I looked at the patch and
>>> also could not understand it.
>>
>> Apologies, it may not be obvious from the code / comments (I'll try to
>> improve that in the next version).
>>
>> Let's say we're joining "F" with dimensions D1, D2, D3. Then the
>> starjoins_canonicalize() finds the cluster, and picks a canonical join
>> order. Could be [F, D1, D2, D3] - in this order. Or whatever other
>> permutation of the dimensions, it's all equal.
> 
> Uh, are D1, D2, D3 in relid order at this point?
> 

I don't think the patch is explicitly enforcing relid order. It might be
using it indirectly due to how it walks the relations, but there's
nothing particularly special about relid order.

>> Then starjoin_order_invalid() ensures that whatever join relation we
>> produce, it only even contains a prefix of this list. So a join relation
>> can contain [F], [F, D1], [F, D1, D2], [F, D1, D2, D3]. But it can't
>> contain e.g. [F, D2], because that skips the D1 - it's not a prefix.
> 
> Okay, prefix like a multi-column index prefix of columns.
> 

Right.

>> The patch only applies this to relations from the cluster. There can be
>> other relations in the join "in between" the dimensions - that does not
>> make the join order "invalid".
>>
>> So for example there may be joins to non-dimensions A and B, and we will
>> consider joins [F, A, D1, B, D2, D3] and so on as valid. The joins to A
>> and B joins can increase/decrease cardinality, but thanks to this we
>> should find the right place to join the dimensions.
> 
> Okay, so if D1, D2, and D3 are all "cluster" joins then aren't they are
> 1:1, so why would you ever put something like B between them?  If B
> reduces columns, it would be before the cluster, and if it expands them
> it would be after cluster.  So if B is 1:1 too, in what cases might it
> be better to join B between dimension joins?
> 

Right.

>> We could even make it a bit stricter, and require that all dimensions
>> join "at once". I.e. after joining a dimension, only dimensions can be
>> joined (until all dimensions are joined). So [F, D1, A, D2] would not be
>> allowed. This would further reduce the number of join orders considered.
> 
> Right, I guess that is what I am asking above.
> 

You're right. It's simply not implemented.

>>> Impressive.
>>>
>>
>> Indeed. I like how it fits into the existing approach. It's a bit like
>> having yet another "join order restriction".
> 
> This would be a big feature improvement for OLAP workloads.
> 

It would be helpful for many queries, yes. Although I want to point out
those queries usually do other stuff (other non-dimension joins, ...),
and actually process data (while the benchmark matches no rows in the
fact table, which amplifies the planning part). So in practice the
improvements would be smaller.


regards

-- 
Tomas Vondra


Re: should we have a fast-path planning for OLTP starjoins?

От:
Tomas Vondra <tomas@vondra.me>
Дата:
On 6/1/26 16:00, Robert Haas wrote:
> On Thu, May 28, 2026 at 6:11 PM Tomas Vondra  wrote:
>> Determine if the query includes a starjoin (or multiple), and remember
>> the relids included in the starjoin cluster. Pick a "canonical" join
>> order for each starjoin cluster we found (e.g. with dimensions in relid
>> order).
> 
> I like the idea of trying to avoid considering a bunch of join orders
> that are not meaningfully different from each other, but I think we're
> only really guaranteed that two join orders are equivalent if both of
> them are exactly one-to-one, with the row count neither increasing nor
> decreasing. (Even then, it's not 100% equivalent, but probably close
> enough.) I don't remember off-hand whether your definition of starjoin
> also includes joins that can reduce the row count. If it does, then I
> think we might need to be smarter than just putting the dimensions in
> relid order.

For the purpose of this optimization, the dimensions have to be 1:1
joins. There must not be any additional restrictions, it needs to be a
join on a FK, etc. So the relid order works fine.

> If it does not, then maybe we need to think about whether
> the optimization is going to apply to a sufficiently broad range of
> cases. Maybe it's fine: if a fact table is joined to lots of dimension
> tables, then some of them might have restriction clauses but probably
> many of them won't.
> 

In my experience it does apply to a significant number of queries, but
there's a selection bias (people don't talk to me about queries that
have no problems). Still, if the optimization costs virtually nothing, I
don't think that's a problem (we already do stuff like matching joins to
FK constraints anyway).

Also, I think there are ways to use this optimization to more queries.
For example it directly extends to snowflake joins - by adding "layers"
of dimensions, recursively. It's not such a massive benefit, because
snowflake joins have restrictions that substantially limit the search
space. But it would allow increasing join_collapse_limit.

The other idea is that Joel Jacobson's patch with KEY joins might allow
proving more joins are 1:1, not just joins on foreign keys. But I
haven't thought about that very much, and I'm not sure it's very useful
for such joins (it's probably not a starjoin-like query, and does not
have so many number of join orders).

> This is making me wonder whether we could improve on GEQO by
> transforming it from a "plan this query" thing to a "restrict the join
> order" thing. For instance, suppose we have two tables T1 and T2 and
> we wonder whether swapping the order in which they are joined matters.
> We pick a few random partial join orders of tables in the query
> excluding T1 and T2 and then check whether appending T1 and then T2
> produces significantly different results from appending T2 and then
> T1. So for example say we pick (), (T3), (T3-T4), and (T5-T3). We then
> test the cost/row count of T1-T2 vs. T2-T1, the cost/row count of
> T3-T1-T2 vs. T3-T2-T1, similarly for T3-T4-T1-T2 vs. T3-T4-T2-T1,
> similarly for T5-T3-T1-T2 vs. T5-T3-T2-T1. If we see that swapping the
> order of T1 and T2 routinely has minimal effect on the outcome, then
> it's probably safe to pick one or the other to be joined first and
> disregard all the join orders where the two are swapped. By repeating
> this kind of testing for various pairs of tables, we could possibly
> prune the join search space for large join problems considerably, and
> then still do an exhaustive test of the remaining join orders. Maybe
> that would produce better results than GEQO currently does (or maybe
> not).
> 

I'm not opposed to improving GEQO, but I don't think it's an alternative
to this optimization. It's still going to be a heuristics that skips
parts of the search space too early. 99.999% of deployments are not even
using GEQO for any queries.

The optimization helps a lot both in cases where GEQO is not applicable
(with fewer than geqo_threshold, and I doubt we want to lower that), and
in cases where GEQO is supposed to be helpful (i.e. it beats GEQO with
many joins).

So I think it's orthogonal, and it might even mean we don't need GEQO as
often. In any case, I see this as an orthogonal discussion. There's
already a thread discussing changes to GEQO, or replacing it with a new
heuristics.

> Although I kind of like this idea and think it's interesting, it's
> probably not going to be a good enough idea to compete with what
> you're doing, because your idea is working even when the number of
> dimensions is very small, and this seems like it would be a
> significantly more expensive test. So the question is probably whether
> there are cases where your cheaper test loses too much. I'm not sure
> of the answer. My intuition is that join planning is pretty hard and
> that shortcuts will tend to have cases where they behave really badly,
> but my intuition is also that we are wasting a whole lot of CPU cycles
> testing cases that are nearly equivalent to each other. I'm not sure
> which of those two intuitions is more correct in this case.
> 

Right, exactly. I agree this needs some testing how much overhead this
adds to large queries that don't benefit from it. I'll do that, but I
don't expect that to be an issue (because we already do the heavy work
of matching the FKeys already). It might require a smarter way to
represent the clusters or some other optimizations, of course.


regards

-- 
Tomas Vondra



Re: should we have a fast-path planning for OLTP starjoins?

От:
"Joel Jacobson" <joel@compiler.org>
Дата:
On Mon, Jun 1, 2026, at 17:35, Tomas Vondra wrote:
> The other idea is that Joel Jacobson's patch with KEY joins might allow
> proving more joins are 1:1, not just joins on foreign keys. But I
> haven't thought about that very much, and I'm not sure it's very useful
> for such joins (it's probably not a starjoin-like query, and does not
> have so many number of join orders).

I find this thread very interesting, and like Tomas explained,
I'm interested in examining if there could possibly be an opportunity
for some shared infrastructure here.  I intend to conduct such research
in the upcoming weeks, and report back with my findings.

Just to clarify one thing; a key join is always backed by an underlying
foreign key (referential constraint). What I think Tomas means with
"not just joins on foreign keys" is that that key joins not only works
between two base tables, but also through derived tables.
To explain what that means, maybe an example is easiest,
a good one I recommend is: https://keyjoin.org/#sec7.3.1

/Joel


FAQ