Skip to content

Optionally estimate composite-key equijoins together - #2339

Open
chenjinbao1989 wants to merge 1 commit into
apache:mainfrom
chenjinbao1989:pr-composite-key-join-sel
Open

chenjinbao1989 wants to merge 1 commit into
apache:mainfrom
chenjinbao1989:pr-composite-key-join-sel

Conversation

@chenjinbao1989

@chenjinbao1989 chenjinbao1989 commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

With several equality clauses between the same two relations, like

cs_item_sk = cr_item_sk AND cs_order_number = cr_order_number

clauselist_selectivity() multiplies the clauses' selectivities, assuming the columns are independent. For a composite key that is off by orders of magnitude. In TPC-DS at scale factor 10, every catalog_returns row matches exactly one catalog_sales row, 1.44M in total, but the estimate is 1/102000 * 1/1.33M of the cross product, about 150 rows. In query 64 that propagates upwards: the join of store_sales to the aggregate over it is estimated at 4947 rows instead of 2M, and the planner chooses a plan that redistributes ~2M rows several times, believing them to be ~20.

gp_selectivity_damping_for_joins improves q64, but damps every multi-clause join, and makes q14 and q06 slower.

Add gp_composite_key_join_selectivity (off by default). When enabled, calc_joinrel_size_estimate() calls the new
get_composite_key_join_selectivity() after the foreign key estimation, and in the same way, for inner joins: it groups the equality clauses between the same pair of base relations, and for groups of two or more, estimates the number of distinct combinations of the columns on each side as the product of the columns' ndistinct, clamped to the number of rows. The combined selectivity is 1 / max(combinations on either side), the containment assumption of eqjoinsel. It's used only where it's larger than the product of the clause selectivities, i.e. where that product would be impossibly small, and never more than the selectivity of the most selective clause. Otherwise the clauses are estimated as before.

estimate_num_groups() isn't used for the combinations, because for several columns of one relation it clamps to 10% of the rows, assuming correlation. That's reasonable for GROUP BY, but makes a unique composite key look ten times less selective than it is.

With this, the catalog_sales/catalog_returns join is estimated at 1,439,958 rows; actual 1,439,955. Of the 99 TPC-DS queries, q24, q50, q64 and q85 change plan, at both scale factor 1 and 10. At scale factor 10, q64 goes from 12.7 s to 9.7 s and q24 from 6.9 s to 6.0 s; q50 and q85 don't change much. The results are unchanged.

@Alena0704
Alena0704 self-requested a review November 16, 2026 21:23
@yjhjstz

yjhjstz commented Nov 17, 2026

Copy link
Copy Markdown
Member

Thanks for working on this. The underestimate for composite-key joins is real, and the TPC-DS numbers are convincing. I built the PR head (225e6ea) on a 3-segment cluster and tried some variations of the test case. Four issues came up, each with a self-contained SQL repro below. All runs use optimizer = off. Estimates are taken from the Gather Motion line, so they are totals over all segments.

Setup: the same data as the regression test, plus one extra table.

set optimizer = off;
create table ck_sales (item int, ord int, v int) distributed by (ord);
create table ck_returns (item int, ord int, v int) distributed by (ord);
insert into ck_sales select i % 1000, i / 3, i from generate_series(1, 30000) i;
insert into ck_returns select item, ord, v from ck_sales where v % 10 = 0;
create table ck_x (ord int, w int) distributed by (ord);
insert into ck_x select i, i from generate_series(0, 10000) i;
analyze ck_sales; analyze ck_returns; analyze ck_x;

1. A filter on the key side is cancelled out

combination_ndistinct() clamps the number of combinations to rel->rows, which is the row count after the relation's restriction clauses. The per-column ndistinct values, however, are for the whole table. The restriction selectivity is already included in outer_rows / inner_rows, so clamping to the filtered size cancels it out. The comment in eqjoinsel_semi() describes the same double counting for nd1.

select * from ck_sales s join ck_returns r
  on s.item = r.item and s.ord = r.ord
  where s.v <= 15000;
case GUC off GUC on actual
no filter 15 3000 3000
s.v <= 15000 (50%) 14 3000 1500
s.v <= 3000 (10%) 12 901 300
r.v <= 15000 (50%) 15 1500 1500

Clamping to rel->tuples instead, which is consistent with eqjoinsel_inner(), gives 3000 / 1500 / 300 / 1500. The unfiltered case doesn't change:

-	*result = Min(nd, Max(rel->rows, 1.0));
+	*result = Min(nd, Max(rel->tuples, 1.0));

2. The estimate depends on the FROM order

Clauses are grouped by the pair of relations in the clause that equivclass.c happened to generate. When a key column is also joined to a third table, the generated clause can involve that table instead, and the group is split:

-- estimated 15 with the GUC on
select * from ck_x x join ck_returns r on x.ord = r.ord
                     join ck_sales s on s.item = r.item and s.ord = r.ord;
-- estimated 3000 with the GUC on
select * from ck_returns r join ck_sales s on s.item = r.item and s.ord = r.ord
                           join ck_x x on x.ord = r.ord;
case GUC off GUC on actual
x first 15 15 3000
x last 15 3000 3000

With client_min_messages = debug1, the new DEBUG message appears exactly once in both cases, for the r ⋈ s joinrel. In the first query, the lower r ⋈ s join in the plan is corrected to 3000. The {x, r, s} joinrel, however, gets its size from an input pair in which s.ord = r.ord was generated as x.ord = s.ord, so it stays at 15. A key column that is also joined to a dimension, as in i_item_sk = cs_item_sk, is common.

get_foreign_key_join_selectivity() handles the same situation by matching EC-derived clauses on rinfo->parent_ec rather than on the Vars of the generated clause (see its comment "even if equivclass.c chose to generate a clause equating some other pair of Vars ..."). Doing the same here would make the result independent of the FROM order.

3. Declared PK / FK already give exact estimates

Cloudberry doesn't enforce foreign keys, but it still records them in pg_constraint, and get_foreign_key_join_selectivity() uses them. With the constraints declared, the existing code is exact with the GUC off, including the two cases above:

create table fk_sales (item int, ord int, v int, primary key (item, ord)) distributed by (ord);
create table fk_returns (item int, ord int, v int,
                         foreign key (item, ord) references fk_sales (item, ord)) distributed by (ord);
insert into fk_sales select * from ck_sales;
insert into fk_returns select * from ck_returns;
analyze fk_sales; analyze fk_returns;
case GUC off GUC on actual
no filter 3000 3000 3000
s.v <= 15000 1500 1500 1500
3-way, x first 3000 3000 3000
3-way, x last 3000 3000 3000

The TPC-DS schema defines these keys: catalog_returns (cr_item_sk, cr_order_number) references catalog_sales. Declaring them requires a unique index on the referenced table, which may be unwanted on a large fact table, so the heuristic still has a use. Could you add a run with the constraints declared as a baseline in the description, and mention in the GUC documentation that the heuristic is meant for schemas without such constraints?

4. The product isn't "impossibly small" in general

The comment says the product of the clause selectivities is impossible once the product of the ndistincts exceeds the row count. That only holds if the combinations on one side are contained in those on the other side. This is true for FK-like keys, but not for independent columns, where the product is the right answer:

create table i1 (x int, y int) distributed randomly;
create table i2 (x int, y int) distributed randomly;
insert into i1 select abs(hashint4(i)) % 300, abs(hashint4(i + 7000000)) % 300 from generate_series(1, 20000) i;
insert into i2 select abs(hashint4(i + 3000000)) % 300, abs(hashint4(i + 9000000)) % 300 from generate_series(1, 20000) i;
analyze i1; analyze i2;
select * from i1 join i2 using (x, y);
case GUC off GUC on actual
i1 join i2 using (x, y) 4351 20000 4496

The GUC applies to the whole session, so enabling it for composite-key joins also affects joins like this one. Please state the containment assumption in the comment, the commit message and the GUC description. It might also be worth requiring some evidence that the columns form a key on one side before overriding the product, such as a unique index on them or CREATE STATISTICS (ndistinct).

@chenjinbao1989

Copy link
Copy Markdown
Contributor Author

Thanks for working on this. The underestimate for composite-key joins is real, and the TPC-DS numbers are convincing. I built the PR head (225e6ea) on a 3-segment cluster and tried some variations of the test case. Four issues came up, each with a self-contained SQL repro below. All runs use optimizer = off. Estimates are taken from the Gather Motion line, so they are totals over all segments.

Setup: the same data as the regression test, plus one extra table.

set optimizer = off;
create table ck_sales (item int, ord int, v int) distributed by (ord);
create table ck_returns (item int, ord int, v int) distributed by (ord);
insert into ck_sales select i % 1000, i / 3, i from generate_series(1, 30000) i;
insert into ck_returns select item, ord, v from ck_sales where v % 10 = 0;
create table ck_x (ord int, w int) distributed by (ord);
insert into ck_x select i, i from generate_series(0, 10000) i;
analyze ck_sales; analyze ck_returns; analyze ck_x;

1. A filter on the key side is cancelled out

combination_ndistinct() clamps the number of combinations to rel->rows, which is the row count after the relation's restriction clauses. The per-column ndistinct values, however, are for the whole table. The restriction selectivity is already included in outer_rows / inner_rows, so clamping to the filtered size cancels it out. The comment in eqjoinsel_semi() describes the same double counting for nd1.

select * from ck_sales s join ck_returns r
  on s.item = r.item and s.ord = r.ord
  where s.v <= 15000;

case GUC off GUC on actual
no filter 15 3000 3000
s.v <= 15000 (50%) 14 3000 1500
s.v <= 3000 (10%) 12 901 300
r.v <= 15000 (50%) 15 1500 1500
Clamping to rel->tuples instead, which is consistent with eqjoinsel_inner(), gives 3000 / 1500 / 300 / 1500. The unfiltered case doesn't change:

-	*result = Min(nd, Max(rel->rows, 1.0));
+	*result = Min(nd, Max(rel->tuples, 1.0));

2. The estimate depends on the FROM order

Clauses are grouped by the pair of relations in the clause that equivclass.c happened to generate. When a key column is also joined to a third table, the generated clause can involve that table instead, and the group is split:

-- estimated 15 with the GUC on
select * from ck_x x join ck_returns r on x.ord = r.ord
                     join ck_sales s on s.item = r.item and s.ord = r.ord;
-- estimated 3000 with the GUC on
select * from ck_returns r join ck_sales s on s.item = r.item and s.ord = r.ord
                           join ck_x x on x.ord = r.ord;

case GUC off GUC on actual
x first 15 15 3000
x last 15 3000 3000
With client_min_messages = debug1, the new DEBUG message appears exactly once in both cases, for the r ⋈ s joinrel. In the first query, the lower r ⋈ s join in the plan is corrected to 3000. The {x, r, s} joinrel, however, gets its size from an input pair in which s.ord = r.ord was generated as x.ord = s.ord, so it stays at 15. A key column that is also joined to a dimension, as in i_item_sk = cs_item_sk, is common.

get_foreign_key_join_selectivity() handles the same situation by matching EC-derived clauses on rinfo->parent_ec rather than on the Vars of the generated clause (see its comment "even if equivclass.c chose to generate a clause equating some other pair of Vars ..."). Doing the same here would make the result independent of the FROM order.

3. Declared PK / FK already give exact estimates

Cloudberry doesn't enforce foreign keys, but it still records them in pg_constraint, and get_foreign_key_join_selectivity() uses them. With the constraints declared, the existing code is exact with the GUC off, including the two cases above:

create table fk_sales (item int, ord int, v int, primary key (item, ord)) distributed by (ord);
create table fk_returns (item int, ord int, v int,
                         foreign key (item, ord) references fk_sales (item, ord)) distributed by (ord);
insert into fk_sales select * from ck_sales;
insert into fk_returns select * from ck_returns;
analyze fk_sales; analyze fk_returns;

case GUC off GUC on actual
no filter 3000 3000 3000
s.v <= 15000 1500 1500 1500
3-way, x first 3000 3000 3000
3-way, x last 3000 3000 3000
The TPC-DS schema defines these keys: catalog_returns (cr_item_sk, cr_order_number) references catalog_sales. Declaring them requires a unique index on the referenced table, which may be unwanted on a large fact table, so the heuristic still has a use. Could you add a run with the constraints declared as a baseline in the description, and mention in the GUC documentation that the heuristic is meant for schemas without such constraints?

4. The product isn't "impossibly small" in general

The comment says the product of the clause selectivities is impossible once the product of the ndistincts exceeds the row count. That only holds if the combinations on one side are contained in those on the other side. This is true for FK-like keys, but not for independent columns, where the product is the right answer:

create table i1 (x int, y int) distributed randomly;
create table i2 (x int, y int) distributed randomly;
insert into i1 select abs(hashint4(i)) % 300, abs(hashint4(i + 7000000)) % 300 from generate_series(1, 20000) i;
insert into i2 select abs(hashint4(i + 3000000)) % 300, abs(hashint4(i + 9000000)) % 300 from generate_series(1, 20000) i;
analyze i1; analyze i2;
select * from i1 join i2 using (x, y);

case GUC off GUC on actual
i1 join i2 using (x, y) 4351 20000 4496
The GUC applies to the whole session, so enabling it for composite-key joins also affects joins like this one. Please state the containment assumption in the comment, the commit message and the GUC description. It might also be worth requiring some evidence that the columns form a key on one side before overriding the product, such as a unique index on them or CREATE STATISTICS (ndistinct).

I tried to reproduce this issue, but with the same SQL I got correct results every time, whether gp_composite_key_join_selectivity was set to on or off.

@lss602726449

Copy link
Copy Markdown
Contributor

Thanks for working on this. The underestimate for composite-key joins is real, and the TPC-DS numbers are convincing. I built the PR head (225e6ea) on a 3-segment cluster and tried some variations of the test case. Four issues came up, each with a self-contained SQL repro below. All runs use optimizer = off. Estimates are taken from the Gather Motion line, so they are totals over all segments.

Setup: the same data as the regression test, plus one extra table.

set optimizer = off;
create table ck_sales (item int, ord int, v int) distributed by (ord);
create table ck_returns (item int, ord int, v int) distributed by (ord);
insert into ck_sales select i % 1000, i / 3, i from generate_series(1, 30000) i;
insert into ck_returns select item, ord, v from ck_sales where v % 10 = 0;
create table ck_x (ord int, w int) distributed by (ord);
insert into ck_x select i, i from generate_series(0, 10000) i;
analyze ck_sales; analyze ck_returns; analyze ck_x;

1. A filter on the key side is cancelled out

combination_ndistinct() clamps the number of combinations to rel->rows, which is the row count after the relation's restriction clauses. The per-column ndistinct values, however, are for the whole table. The restriction selectivity is already included in outer_rows / inner_rows, so clamping to the filtered size cancels it out. The comment in eqjoinsel_semi() describes the same double counting for nd1.

select * from ck_sales s join ck_returns r
  on s.item = r.item and s.ord = r.ord
  where s.v <= 15000;

case GUC off GUC on actual
no filter 15 3000 3000
s.v <= 15000 (50%) 14 3000 1500
s.v <= 3000 (10%) 12 901 300
r.v <= 15000 (50%) 15 1500 1500
Clamping to rel->tuples instead, which is consistent with eqjoinsel_inner(), gives 3000 / 1500 / 300 / 1500. The unfiltered case doesn't change:

-	*result = Min(nd, Max(rel->rows, 1.0));
+	*result = Min(nd, Max(rel->tuples, 1.0));

2. The estimate depends on the FROM order

Clauses are grouped by the pair of relations in the clause that equivclass.c happened to generate. When a key column is also joined to a third table, the generated clause can involve that table instead, and the group is split:

-- estimated 15 with the GUC on
select * from ck_x x join ck_returns r on x.ord = r.ord
                     join ck_sales s on s.item = r.item and s.ord = r.ord;
-- estimated 3000 with the GUC on
select * from ck_returns r join ck_sales s on s.item = r.item and s.ord = r.ord
                           join ck_x x on x.ord = r.ord;

case GUC off GUC on actual
x first 15 15 3000
x last 15 3000 3000
With client_min_messages = debug1, the new DEBUG message appears exactly once in both cases, for the r ⋈ s joinrel. In the first query, the lower r ⋈ s join in the plan is corrected to 3000. The {x, r, s} joinrel, however, gets its size from an input pair in which s.ord = r.ord was generated as x.ord = s.ord, so it stays at 15. A key column that is also joined to a dimension, as in i_item_sk = cs_item_sk, is common.

get_foreign_key_join_selectivity() handles the same situation by matching EC-derived clauses on rinfo->parent_ec rather than on the Vars of the generated clause (see its comment "even if equivclass.c chose to generate a clause equating some other pair of Vars ..."). Doing the same here would make the result independent of the FROM order.

3. Declared PK / FK already give exact estimates

Cloudberry doesn't enforce foreign keys, but it still records them in pg_constraint, and get_foreign_key_join_selectivity() uses them. With the constraints declared, the existing code is exact with the GUC off, including the two cases above:

create table fk_sales (item int, ord int, v int, primary key (item, ord)) distributed by (ord);
create table fk_returns (item int, ord int, v int,
                         foreign key (item, ord) references fk_sales (item, ord)) distributed by (ord);
insert into fk_sales select * from ck_sales;
insert into fk_returns select * from ck_returns;
analyze fk_sales; analyze fk_returns;

case GUC off GUC on actual
no filter 3000 3000 3000
s.v <= 15000 1500 1500 1500
3-way, x first 3000 3000 3000
3-way, x last 3000 3000 3000
The TPC-DS schema defines these keys: catalog_returns (cr_item_sk, cr_order_number) references catalog_sales. Declaring them requires a unique index on the referenced table, which may be unwanted on a large fact table, so the heuristic still has a use. Could you add a run with the constraints declared as a baseline in the description, and mention in the GUC documentation that the heuristic is meant for schemas without such constraints?

4. The product isn't "impossibly small" in general

The comment says the product of the clause selectivities is impossible once the product of the ndistincts exceeds the row count. That only holds if the combinations on one side are contained in those on the other side. This is true for FK-like keys, but not for independent columns, where the product is the right answer:

create table i1 (x int, y int) distributed randomly;
create table i2 (x int, y int) distributed randomly;
insert into i1 select abs(hashint4(i)) % 300, abs(hashint4(i + 7000000)) % 300 from generate_series(1, 20000) i;
insert into i2 select abs(hashint4(i + 3000000)) % 300, abs(hashint4(i + 9000000)) % 300 from generate_series(1, 20000) i;
analyze i1; analyze i2;
select * from i1 join i2 using (x, y);

case GUC off GUC on actual
i1 join i2 using (x, y) 4351 20000 4496
The GUC applies to the whole session, so enabling it for composite-key joins also affects joins like this one. Please state the containment assumption in the comment, the commit message and the GUC description. It might also be worth requiring some evidence that the columns form a key on one side before overriding the product, such as a unique index on them or CREATE STATISTICS (ndistinct).

I have also reproduce this. Just add these test to regress to see it reproduce or not.

@chenjinbao1989

Copy link
Copy Markdown
Contributor Author

@yjhjstz @lss602726449
Regarding the first issue, this behavior is expected. Cloudberry has no cross-table statistics between the corresponding columns of ck_sales and ck_returns. So we can only estimate the number of distinct values (NDV) within a single table. We can't use the NDV of ck_sales to infer the NDV of ck_returns. I plan to look into adding statistics on the relationship between the two tables in the future.

@chenjinbao1989
chenjinbao1989 force-pushed the pr-composite-key-join-sel branch from 5189d54 to 1d89a42 Compare November 23, 2026 21:31
@chenjinbao1989

Copy link
Copy Markdown
Contributor Author

@yjhjstz @lss602726449
issue #2 #4 have been fixed

@chenjinbao1989
chenjinbao1989 force-pushed the pr-composite-key-join-sel branch from 1d89a42 to 8da6ff2 Compare November 24, 2026 02:09
Comment thread src/backend/optimizer/path/costsize.c Resolved
With several equality clauses between the same two relations, like

    cs_item_sk = cr_item_sk AND cs_order_number = cr_order_number

clauselist_selectivity() multiplies the clauses' selectivities, assuming
the columns are independent. For a composite key that is off by orders of
magnitude. In TPC-DS at scale factor 10, every catalog_returns row matches
exactly one catalog_sales row, 1.44M in total, but the estimate is
1/102000 * 1/1.33M of the cross product, about 150 rows. In query 64 that
propagates upwards: the join of store_sales to the aggregate over it is
estimated at 4947 rows instead of 2M, and the planner chooses a plan that
redistributes ~2M rows several times, believing them to be ~20.

gp_selectivity_damping_for_joins improves q64, but damps every
multi-clause join, and makes q14 and q06 slower.

Add gp_composite_key_join_selectivity (on by default). When enabled,
calc_joinrel_size_estimate() calls the new
get_composite_key_join_selectivity() after the foreign key estimation, and
in the same way, for inner joins: it groups the equality clauses between
the same pair of base relations, and for groups of two or more, estimates
the number of distinct combinations of the columns on each side as the
product of the columns' ndistinct, clamped to the number of rows. The
combined selectivity is 1 / max(combinations on either side), the
containment assumption of eqjoinsel, applied to the combinations.

That is a much stronger assumption than containment of each column's
values. With independent columns of 300 values each, two tables of 20000
rows have about a fifth of the 90000 combinations each, and the product
of the selectivities estimates the 4496 matching rows right; the combined
selectivity would say 20000. The statistics can't tell that from a
composite key, so the combined selectivity is used only where the product
is less than 1/100 of it: when the combinations are that much fewer than
the product of the columns' ndistinct, few rows would match by chance,
and the join is most likely on a key. It's never more than the
selectivity of the most selective clause. Otherwise the clauses are
estimated as before.

estimate_num_groups() isn't used for the combinations, because for several
columns of one relation it clamps to 10% of the rows, assuming correlation.
That's reasonable for GROUP BY, but makes a unique composite key look ten
times less selective than it is.

The size of a join relation is estimated once, from the first pair of
inputs it's built from, so the clauses seen depend on the join order.
With x.ord = r.ord AND s.ord = r.ord AND s.item = r.item, joining {x, r}
to s gets x.ord = s.ord from the equivalence class, which doesn't go with
s.item = r.item. So a clause generated from an equivalence class can also
join any other members of the class on the two sides, and the pair of
relations with the most clauses is estimated first.

With this, the catalog_sales/catalog_returns join is estimated at
1,439,958 rows; actual 1,439,955. Of the 99 TPC-DS queries, q24, q50, q64
and q85 change plan, at both scale factor 1 and 10. At scale factor 10,
q64 goes from 12.7 s to 9.7 s and q24 from 6.9 s to 6.0 s; q50 and q85
don't change much. The results are unchanged.
@chenjinbao1989
chenjinbao1989 force-pushed the pr-composite-key-join-sel branch from 3f296e2 to 1713ef0 Compare November 24, 2026 05:02
-- But not independent columns with few values: the tables have about a fifth
-- of the 90000 combinations each, and 4496 rows match, as multiplying the
-- selectivities estimates, not 20000.
create table ck_i1 (x int, y int) distributed randomly;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The 1% ratio guard only protects low-cardinality independent columns. With independent high-cardinality columns it still fires:
a1/a2: 20000 rows each, x,y = abs(hashint4(..)) % 2000 independently
select * from a1 join a2 using (x, y);
GUC off: est 100, GUC on: est 20000, actual 103
Joins of two fact tables on (customer_sk, date_sk) look exactly like this. Could we require some evidence of a key on one side (unique index/PK, or extended ndistinct statistics) before overriding the product, or at least keep it off by default and document the containment assumption?

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants