Skip to content

Optionally estimate composite-key equijoins together - #2339

Open
chenjinbao1989 wants to merge 2 commits into
apache:mainfrom
chenjinbao1989:pr-composite-key-join-sel
Open

chenjinbao1989 wants to merge 2 commits 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
@chenjinbao1989
chenjinbao1989 force-pushed the pr-composite-key-join-sel branch 2 times, most recently 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?

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 estimates each group of two or more
as eqjoinsel() estimates one clause, as if the columns on each side were
one column of their combinations: 1 / max(combinations on either side).

Like eqjoinsel(), that assumes that the combinations of the side with
fewer of them all occur on the other side. No statistics tell that, with
one clause or two: there are none about two relations together. What two
clauses add is how the columns of each relation are correlated, which
decides the number of combinations. That's taken from extended ndistinct
statistics on the columns, if there are any; otherwise the columns are
assumed independent within the relation, and the number is the product of
their ndistinct. Either way, it's clamped to the number of rows.
estimate_num_groups() isn't used, because without extended statistics it
clamps several columns of one relation 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.

Fewer combinations than the product of the ndistinct don't always mean a
key, though. 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, as eqjoinsel() does for a single
column with those values. So the combined selectivity is used only where
the product is less than 1/100 of it: when the combinations are that much
fewer, 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. With many values,
independent columns pass that test too: two tables of 20000 rows with
2000 values in each column are estimated at 20000 matching rows instead of
103, as eqjoinsel() estimates a single column of the combinations.

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.
get_composite_key_join_selectivity() estimates a group of equijoin
clauses between two relations as 1 / max(combinations on either side),
if multiplying their selectivities gives less than 1/100 of that. With
many values, independent columns pass that test: two tables of 20000
rows with two independent columns of 2000 values each have almost only
unique combinations, and 103 rows match, but the join was estimated at
20000 rows, as eqjoinsel() estimates a single column of the
combinations.

The number of combinations alone doesn't tell independent columns from
a key: with few rows per value, both have mostly unique combinations.
What does is how many combinations a value of one column has compared
to how many it would have if the columns were independent. Take x, the
column with the most distinct values, and the others as one column y.
A value of x has r = rows / ndistinct(x) rows and k = combinations /
ndistinct(x) combinations; if y were independent of x, its rows would
have k_ind = ndistinct(y) * (1 - (1 - 1/ndistinct(y))^r) distinct values
of y. If k_ind >= 2, and k >= k_ind^0.9, the columns look independent.

If the statistics of both relations show that, the combinations of each
are as if chosen at random, and the two sides have about as many in
common as the product of the selectivities says, so the clauses are
estimated as before. Without measured numbers of combinations, the
number is the product of the numbers of distinct values, which says
nothing about how the columns are correlated, and nothing changes. Nor
if one side has too few rows per value to tell, like a table of returns
with one or two lines per order, which can be on a key as well as not:
the catalog_sales/catalog_returns join is still estimated as a key.

The numbers of combinations are measured by extended ndistinct
statistics, if they've been created. With gp_analyze_hash_sample (off by
default), ANALYZE also keeps enough to estimate them at plan time for
any of the columns that could be part of a composite key: those with
ndistinct of at least 1% of the rows and a hashable type, at most 32 per
table. Each of them stores the hashes of its values in the same 3000 of
the sampled rows, so a column stores one array however many others it
can be combined with, and three columns can be combined as well as two.
In a simulation of 18 cases, with five samples each, combinations
estimated from 3000 rows decided the test as those from the whole
sample of 30000 in all 90 runs; from 1000 rows they didn't in 4.

The hashes are stored in a free slot of each column's pg_statistic row,
as a new kind, STATISTIC_KIND_HASH_SAMPLE, so there is no catalog change.
They are stanumbers, which gpsd and minirepro dump and restore as they
are whatever the column's type: 24 bits of the hash of each value, which
float4 represents exactly, 0 for NULL. The first number is a checksum of
the hashes of all the columns in all the rows, and the planner combines
only columns with the same checksum: not after an ANALYZE of only some
of them. The rows are ordered by their values, so a table of no more
than 3000 rows keeps the same ones in the same order, and the same
checksum, however it's analyzed.

Leaf partitions are skipped: the planner seldom joins a partition by
itself, and their last slot is taken by hyperloglog counters. A
partitioned table whose statistics are merged from those of its
partitions, without a sample, takes a sample of 3000 rows for this. That
makes ANALYZE of a table of 3M rows in 12 partitions about 5% slower.

The planner estimates the combinations of two to eight columns of a
relation from their hashes, with the estimator of extended ndistinct
statistics, where there are no extended statistics on them.

A table joined to itself, or to a subset of itself, has the same
combinations on both sides, however independent its columns look, and
the product of the selectivities underestimates such joins by orders of
magnitude: a store_sales self-join on its ticket number and item was
estimated about 7000 times too low. So the test is skipped when both
sides are the same table, and the join is estimated as a composite key.

With this, the example above is estimated at about 100 rows, with
extended statistics or the hashes, also with both tables partitioned,
and its self-join at 20247 (actual 20116). Over the 18 cases, without
extended statistics, the geometric mean error goes from 34.6x to 20.4x
with the hashes.
@chenjinbao1989
chenjinbao1989 force-pushed the pr-composite-key-join-sel branch from 1713ef0 to 2702b14 Compare November 29, 2026 16:15
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