Enable partitionwise join for partition keys wrapped by RelabelType

Started by Matheus Alcantara12 months ago17 messageshackers

Thread notes

1 note#performance#moderate#enhancement
hackorum-bot#performance#moderate#enhancement
hackorum-bot
2 days ago

@global #performance #moderate #enhancement

#performance#moderate#enhancement
Jump to latest
#1Matheus Alcantara
matheusssilv97@gmail.com

Hi,

The function exprs_known_equal() is used by the planner to determine if
two expressions are semantically equivalent, often by checking if they
belong to the same Equivalence Class (EC).

When a partitioned table uses a varchar(N) type as a partition key, the
partition key expression stored in the equivalence class member
(em->em_expr) is often wrapped in a RelabelType node.

However, when checking a join condition or a predicate against the EC
member, the input expression (item1 or item2) may not contain this
RelabelType wrapper, leading to an incorrect equal() comparison and
failing to detect a known equivalence. This prevents the planner from
recognizing that a join condition matches the partition keys, thereby
disabling optimizations like partitionwise joins.

On match_expr_to_partition_keys() we already strip away any RelabelType
that is present on OpExpr, so I think that can also modify
exprs_known_equal() to do the same and enable partitionwise joins for
more cases. Please see the attached patch.

On master for queries like the following we have this plan:

EXPLAIN(VERBOSE, COSTS OFF) SELECT fprt3.a, fprt4.a FROM fprt3 JOIN
fprt4 ON fprt3.c = fprt4.c WHERE fprt3.c = '0002';
QUERY PLAN
---------------------------------------------------------------------------------
Nested Loop
Output: fprt3.a, fprt4.a
-> Foreign Scan on public.fprt3_p2 fprt3
Output: fprt3.a, fprt3.c
Remote SQL: SELECT a, c FROM public.fprt3_ft WHERE ((c = '0002'))
-> Materialize
Output: fprt4.a, fprt4.c
-> Foreign Scan on public.fprt4_p2 fprt4
Output: fprt4.a, fprt4.c
Remote SQL: SELECT a, c FROM public.fprt4_ft WHERE ((c = '0002'))
(10 rows)

With the patch and "enable_partitionwise_join" set to on we get this query plan
QUERY PLAN
---------------------------------------------------------------------------------
Foreign Scan
Output: fprt3.a, fprt4.a
Relations: (public.fprt3_p2 fprt3) INNER JOIN (public.fprt4_p2 fprt4)
Remote SQL: SELECT r4.a, r5.a FROM (public.fprt3_ft r4 INNER JOIN public.fprt4_ft r5 ON (((r5.c = '0002')) AND ((r4.c = '0002'))))
(4 rows)

--
Matheus Alcantara
EDB: http://www.enterprisedb.com

Attachments:

v1-0001-Enable-partitionwise-join-for-partition-keys-wrap.patchtext/plain; charset=utf-8; name=v1-0001-Enable-partitionwise-join-for-partition-keys-wrap.patchDownload+44-3
#2jian he
jian.universality@gmail.com
In reply to: Matheus Alcantara (#1)
Re: Enable partitionwise join for partition keys wrapped by RelabelType

On Mon, Dec 15, 2025 at 10:46 PM Matheus Alcantara
<matheusssilv97@gmail.com> wrote:

Hi,

The function exprs_known_equal() is used by the planner to determine if
two expressions are semantically equivalent, often by checking if they
belong to the same Equivalence Class (EC).

hi.

src/include/nodes/primnodes.h CollateExpr comments:
/*----------
* CollateExpr - COLLATE
*
* The planner replaces CollateExpr with RelabelType during expression
* preprocessing, so execution never sees a CollateExpr.
*----------
*/

examine_variable handling RelabelType (transformed from CollateExpr) is wrong, i
think. Roughly speaking it will reduce "t2.c collate case_insensitive" to
"t2.c". see [1]/messages/by-id/CACJufxGLCiyhM+P0gxesg2x--PTrMY3PszqSqOq_H4QS_oq3Jg@mail.gmail.com.

If examine_variable does not strip the RelabelType(CollateExpr) node, then
estimate_num_groups->add_unique_group_var may need to deal with RelabelType.

The estimate_num_groups function should account for collation settings. "GROUP
BY a" and "GROUP BY a COLLATE case_insensitive" may result in different row
estimates and should be handled distinctly. Therefore exprs_known_equal within
add_unique_group_var must ensure collation is compared before assuming equality.

In this context, while strippping RelabelType, we should ensure
exprCollation(RelabelType->arg) is the same as the RelabelType->resultcollid.

However, it does not affect partitionwise join, because commit [2]https://git.postgresql.org/cgit/postgresql.git/commit/?id=075acdd93388c080c0fb0aca5723144ad7a56dac already fixed
the collation issue. so we don't have to worry about
have_partkey_equi_join->exprs_known_equal code path for the RelabelType node.

so i change exprs_known_equal to:

+            /* Remove any relabel decorations if collation match */
+            if (IsA(expr, RelabelType))
+            {
+                RelabelType *relabel = castNode(RelabelType, expr);
+                Expr       *rexpr = (Expr *) relabel;
+
+                while (rexpr && IsA(rexpr, RelabelType))
+                    rexpr = ((RelabelType *) rexpr)->arg;
+
+                if (exprCollation((Node *) rexpr) == relabel->resultcollid)
+                    expr = rexpr;
+            }

[1]: /messages/by-id/CACJufxGLCiyhM+P0gxesg2x--PTrMY3PszqSqOq_H4QS_oq3Jg@mail.gmail.com
[2]: https://git.postgresql.org/cgit/postgresql.git/commit/?id=075acdd93388c080c0fb0aca5723144ad7a56dac

--
jian
https://www.enterprisedb.com

Attachments:

v2-0001-Enable-partitionwise-join-for-partition-keys-wrapped-by-RelabelTy.patchtext/x-patch; charset=US-ASCII; name=v2-0001-Enable-partitionwise-join-for-partition-keys-wrapped-by-RelabelTy.patchDownload+53-3
#3Matheus Alcantara
matheusssilv97@gmail.com
In reply to: jian he (#2)
Re: Enable partitionwise join for partition keys wrapped by RelabelType

On Thu Jan 15, 2026 at 12:30 AM -03, jian he wrote:

On Mon, Dec 15, 2025 at 10:46 PM Matheus Alcantara
<matheusssilv97@gmail.com> wrote:

The function exprs_known_equal() is used by the planner to determine if
two expressions are semantically equivalent, often by checking if they
belong to the same Equivalence Class (EC).

src/include/nodes/primnodes.h CollateExpr comments:
/*----------
* CollateExpr - COLLATE
*
* The planner replaces CollateExpr with RelabelType during expression
* preprocessing, so execution never sees a CollateExpr.
*----------
*/

examine_variable handling RelabelType (transformed from CollateExpr) is wrong, i
think. Roughly speaking it will reduce "t2.c collate case_insensitive" to
"t2.c". see [1].

If examine_variable does not strip the RelabelType(CollateExpr) node, then
estimate_num_groups->add_unique_group_var may need to deal with RelabelType.

The estimate_num_groups function should account for collation settings. "GROUP
BY a" and "GROUP BY a COLLATE case_insensitive" may result in different row
estimates and should be handled distinctly. Therefore exprs_known_equal within
add_unique_group_var must ensure collation is compared before assuming equality.

In this context, while strippping RelabelType, we should ensure
exprCollation(RelabelType->arg) is the same as the RelabelType->resultcollid.

However, it does not affect partitionwise join, because commit [2] already fixed
the collation issue. so we don't have to worry about
have_partkey_equi_join->exprs_known_equal code path for the RelabelType node.

so i change exprs_known_equal to:

+            /* Remove any relabel decorations if collation match */
+            if (IsA(expr, RelabelType))
+            {
+                RelabelType *relabel = castNode(RelabelType, expr);
+                Expr       *rexpr = (Expr *) relabel;
+
+                while (rexpr && IsA(rexpr, RelabelType))
+                    rexpr = ((RelabelType *) rexpr)->arg;
+
+                if (exprCollation((Node *) rexpr) == relabel->resultcollid)
+                    expr = rexpr;
+            }

[1] /messages/by-id/CACJufxGLCiyhM+P0gxesg2x--PTrMY3PszqSqOq_H4QS_oq3Jg@mail.gmail.com
[2] https://git.postgresql.org/cgit/postgresql.git/commit/?id=075acdd93388c080c0fb0aca5723144ad7a56dac

Thanks for taking a look at this.

Although this make sense to me I see difference in row estimation using
your v2 patch for the following example:

CREATE COLLATION case_insensitive (provider = icu, locale = '@colStrength=secondary', deterministic = false);
CREATE DOMAIN d_txt1 AS text collate case_insensitive;
CREATE TABLE t1 (a int, b int, c text) PARTITION BY LIST(c);
CREATE TABLE t1_p1 PARTITION OF t1 FOR VALUES IN ('0000', '0003', '0004', '0010');
CREATE TABLE t1_p2 PARTITION OF t1 FOR VALUES IN ('0001', '0005', '0002', '0009');
CREATE TABLE t1_p3 PARTITION OF t1 FOR VALUES IN ('0006', '0007', '0008', '0011');
INSERT INTO t1 SELECT i, i, to_char(i/50, 'FM0000') FROM generate_series(0, 599, 2) i;
ANALYZE t1;

CREATE TABLE t2 (a int, b int, c d_txt1) PARTITION BY LIST(c);
CREATE TABLE t2_p1 PARTITION OF t2 FOR VALUES IN ('0000', '0003', '0004', '0010');
CREATE TABLE t2_p2 PARTITION OF t2 FOR VALUES IN ('0001', '0005', '0002', '0009');
CREATE TABLE t2_p3 PARTITION OF t2 FOR VALUES IN ('0006', '0007', '0008', '0011');
INSERT INTO t2 SELECT i, i, to_char(i/50, 'FM0000') FROM generate_series(0, 599, 3) i;
ANALYZE t2;

SET enable_partitionwise_join TO true;

V1 patch:

postgres=# select * from check_estimated_rows($$ SELECT FROM t1, t2 WHERE t1.c = t2.c GROUP BY t1.c, t2.c $$);
estimated | actual
-----------+--------
12 | 12

V2 patch:

postgres=# select * from check_estimated_rows($$ SELECT FROM t1, t2 WHERE t1.c = t2.c GROUP BY t1.c, t2.c $$);
estimated | actual
-----------+--------
144 | 12

I've also tried to make the partitions of t1 and t2 as foreign tables
and I got the same row estimation difference.

I'm just wondering if we are missing something?

About the v2 patch:

+			if (IsA(expr, RelabelType))
+			{
+				RelabelType *relabel = castNode(RelabelType, expr);
+				Expr	   *rexpr = (Expr *) relabel;
+
+				while (rexpr && IsA(rexpr, RelabelType))
+					rexpr = ((RelabelType *) rexpr)->arg;
+
+				if (exprCollation((Node *) rexpr) == relabel->resultcollid)
+					expr = rexpr;

I think that unwrapping all Relabel types may ignore intermediate
states. For example, consider Relabel A -> Relabel B -> Base expression:
This code will unwrap Relabel A and Relabel B and check the expression
collation directly on Base expression, shouldn't we check every layer,
e.g Relabel A, Relabel B and Base Expression? Please see the attached v3
version with a simplified version of v2 that also check every layer of a
RelabelType node.

--
Matheus Alcantara
EDB: https://www.enterprisedb.com

Attachments:

t52900_3
v3-0001-Enable-partitionwise-join-for-partition-keys-wrap.patchtext/plain; charset=utf-8; name=v3-0001-Enable-partitionwise-join-for-partition-keys-wrap.patchDownload+50-3
#4jian he
jian.universality@gmail.com
In reply to: Matheus Alcantara (#3)
Re: Enable partitionwise join for partition keys wrapped by RelabelType

On Tue, Jan 27, 2026 at 11:42 PM Matheus Alcantara
<matheusssilv97@gmail.com> wrote:

Although this make sense to me I see difference in row estimation using
your v2 patch for the following example:

CREATE COLLATION case_insensitive (provider = icu, locale = '@colStrength=secondary', deterministic = false);
CREATE DOMAIN d_txt1 AS text collate case_insensitive;
CREATE TABLE t1 (a int, b int, c text) PARTITION BY LIST(c);
CREATE TABLE t1_p1 PARTITION OF t1 FOR VALUES IN ('0000', '0003', '0004', '0010');
CREATE TABLE t1_p2 PARTITION OF t1 FOR VALUES IN ('0001', '0005', '0002', '0009');
CREATE TABLE t1_p3 PARTITION OF t1 FOR VALUES IN ('0006', '0007', '0008', '0011');
INSERT INTO t1 SELECT i, i, to_char(i/50, 'FM0000') FROM generate_series(0, 599, 2) i;
ANALYZE t1;

CREATE TABLE t2 (a int, b int, c d_txt1) PARTITION BY LIST(c);
CREATE TABLE t2_p1 PARTITION OF t2 FOR VALUES IN ('0000', '0003', '0004', '0010');
CREATE TABLE t2_p2 PARTITION OF t2 FOR VALUES IN ('0001', '0005', '0002', '0009');
CREATE TABLE t2_p3 PARTITION OF t2 FOR VALUES IN ('0006', '0007', '0008', '0011');
INSERT INTO t2 SELECT i, i, to_char(i/50, 'FM0000') FROM generate_series(0, 599, 3) i;
ANALYZE t2;

SET enable_partitionwise_join TO true;

V1 patch:

postgres=# select * from check_estimated_rows($$ SELECT FROM t1, t2 WHERE t1.c = t2.c GROUP BY t1.c, t2.c $$);
estimated | actual
-----------+--------
12 | 12

V2 patch:

postgres=# select * from check_estimated_rows($$ SELECT FROM t1, t2 WHERE t1.c = t2.c GROUP BY t1.c, t2.c $$);
estimated | actual
-----------+--------
144 | 12

I've also tried to make the partitions of t1 and t2 as foreign tables
and I got the same row estimation difference.

I'm just wondering if we are missing something?

Hi.

in function process_equivalence, we have:
/*
* Ensure both input expressions expose the desired collation (their types
* should be OK already); see comments for canonicalize_ec_expression.
*/
item1 = canonicalize_ec_expression(item1,
exprType((Node *) item1),
collation);
item2 = canonicalize_ec_expression(item2,
exprType((Node *) item2),
collation);

Let's simplify the test case.
CREATE COLLATION case_insensitive (provider = icu, locale =
'@colStrength=secondary', deterministic = false);
CREATE DOMAIN d_txt1 AS text collate case_insensitive;
CREATE TABLE t3 (a int, b int, c text);
INSERT INTO t3 SELECT i % 12, i, to_char(i/50, 'FM0000') FROM
generate_series(0, 599, 2) i;
ANALYZE t3;
CREATE TABLE t4 (a int, b int, c d_txt1);
INSERT INTO t4 SELECT i % 10, i, to_char(i/50, 'FM0000') FROM
generate_series(0, 599, 3) i;
ANALYZE t4;
EXPLAIN SELECT FROM t3, t4 WHERE t3.c = t4.c GROUP BY t3.c, t4.c;

The ``WHERE t3.c = t4.c `` after the function process_equivalence, it will
produce 2 RELABELTYPE node in EquivalenceClass->ec_members->em_expr and your v1
uncondition strip these two RELABELTYPE, exprs_known_equal will retrun true,
therefore for numdistinct it will think "GROUP BY t3.c, t4.c" is the same as
""GROUP BY t3.c".

However if we not unconditionly strip RELABELTYPE, exprs_known_equal will return
false, therefore "GROUP BY t3.c, t4.c", "t3.c", "t4.c" is not identical, so it
multiply these two distinct numbers. IMHO, That's the reason for
estimate number 144 versus 12.

Please also see the comments in canonicalize_ec_expression.
Actually, I think the comments in canonicalize_ec_expression discourage strip
RelabelType nodes when RelabelType->resultcollid differs from the collation of
RelabelType->arg.

--
jian
https://www.enterprisedb.com/

#5Matheus Alcantara
matheusssilv97@gmail.com
In reply to: jian he (#4)
Re: Enable partitionwise join for partition keys wrapped by RelabelType

On 25/02/26 09:46, jian he wrote:

On Tue, Jan 27, 2026 at 11:42 PM Matheus Alcantara
<matheusssilv97@gmail.com> wrote:

Although this make sense to me I see difference in row estimation using
your v2 patch for the following example:

...

V1 patch:

postgres=# select * from check_estimated_rows($$ SELECT FROM t1, t2 WHERE t1.c = t2.c GROUP BY t1.c, t2.c $$);
estimated | actual
-----------+--------
12 | 12

V2 patch:

postgres=# select * from check_estimated_rows($$ SELECT FROM t1, t2 WHERE t1.c = t2.c GROUP BY t1.c, t2.c $$);
estimated | actual
-----------+--------
144 | 12

I've also tried to make the partitions of t1 and t2 as foreign tables
and I got the same row estimation difference.

I'm just wondering if we are missing something?

Hi.

in function process_equivalence, we have:
/*
* Ensure both input expressions expose the desired collation (their types
* should be OK already); see comments for canonicalize_ec_expression.
*/
item1 = canonicalize_ec_expression(item1,
exprType((Node *) item1),
collation);
item2 = canonicalize_ec_expression(item2,
exprType((Node *) item2),
collation);

Let's simplify the test case.
CREATE COLLATION case_insensitive (provider = icu, locale =
'@colStrength=secondary', deterministic = false);
CREATE DOMAIN d_txt1 AS text collate case_insensitive;
CREATE TABLE t3 (a int, b int, c text);
INSERT INTO t3 SELECT i % 12, i, to_char(i/50, 'FM0000') FROM
generate_series(0, 599, 2) i;
ANALYZE t3;
CREATE TABLE t4 (a int, b int, c d_txt1);
INSERT INTO t4 SELECT i % 10, i, to_char(i/50, 'FM0000') FROM
generate_series(0, 599, 3) i;
ANALYZE t4;
EXPLAIN SELECT FROM t3, t4 WHERE t3.c = t4.c GROUP BY t3.c, t4.c;

The ``WHERE t3.c = t4.c `` after the function process_equivalence, it will
produce 2 RELABELTYPE node in EquivalenceClass->ec_members->em_expr and your v1
uncondition strip these two RELABELTYPE, exprs_known_equal will retrun true,
therefore for numdistinct it will think "GROUP BY t3.c, t4.c" is the same as
""GROUP BY t3.c".

However if we not unconditionly strip RELABELTYPE, exprs_known_equal will return
false, therefore "GROUP BY t3.c, t4.c", "t3.c", "t4.c" is not identical, so it
multiply these two distinct numbers. IMHO, That's the reason for
estimate number 144 versus 12.

Ok, that make sense to me, thanks for pointing this out.

So do you think that v3 attached on [1]/messages/by-id/DFZHIGROJHVS.25OYGENTHBLSM@gmail.com correctly address this?

Please also see the comments in canonicalize_ec_expression.
Actually, I think the comments in canonicalize_ec_expression discourage strip
RelabelType nodes when RelabelType->resultcollid differs from the collation of
RelabelType->arg.

Agree, thanks.

[1]: /messages/by-id/DFZHIGROJHVS.25OYGENTHBLSM@gmail.com
/messages/by-id/DFZHIGROJHVS.25OYGENTHBLSM@gmail.com

--
Matheus Alcantara
EDB: https://www.enterprisedb.com

#6Jan Nidzwetzki
jan@planetscale.com
In reply to: Matheus Alcantara (#3)
Re: Enable partitionwise join for partition keys wrapped by RelabelType

Hello Hackers,

Thanks for the patch, this is a nice planner improvement. The v3 version
applies to the current master branch and check-world passes. I could
also confirm that the provided test case demonstrates the intended
change of the query plan.

-- Master at d78040a469b
jan=# SET enable_partitionwise_join=on;
SET
jan=# EXPLAIN(VERBOSE, COSTS OFF) SELECT fprt3.a, fprt4.a FROM fprt3
JOIN fprt4 ON fprt3.c = fprt4.c WHERE fprt3.c = '0002';
QUERY PLAN
-----------------------------------------------------------------------
Nested Loop
Output: fprt3.a, fprt4.a
-> Foreign Scan on public.fprt3_p2 fprt3
Output: fprt3.a, fprt3.c
Remote SQL: SELECT a, c FROM public.fprt3_ft WHERE ((c = '0002'))
-> Materialize
Output: fprt4.a, fprt4.c
-> Foreign Scan on public.fprt4_p2 fprt4
Output: fprt4.a, fprt4.c
Remote SQL: SELECT a, c FROM public.fprt4_ft WHERE ((c =
'0002'))
(10 rows)

-- With the patch applied
jan=# SET enable_partitionwise_join=on;
SET
jan=# EXPLAIN(VERBOSE, COSTS OFF) SELECT fprt3.a, fprt4.a FROM fprt3
JOIN fprt4 ON fprt3.c = fprt4.c WHERE fprt3.c = '0002';
QUERY PLAN

--------------------------------------------------------------------------------------------------------------------------------------
Foreign Scan
Output: fprt3.a, fprt4.a
Relations: (public.fprt3_p2 fprt3) INNER JOIN (public.fprt4_p2 fprt4)
Remote SQL: SELECT r4.a, r5.a FROM (public.fprt3_ft r4 INNER JOIN
public.fprt4_ft r5 ON (((r5.c = '0002')) AND ((r4.c = '0002'))))
(4 rows)

On 27.01.26 16:42, Matheus Alcantara wrote:

I think that unwrapping all Relabel types may ignore intermediate
states. For example, consider Relabel A -> Relabel B -> Base expression:
This code will unwrap Relabel A and Relabel B and check the expression
collation directly on Base expression, shouldn't we check every layer,
e.g Relabel A, Relabel B and Base Expression? Please see the attached v3
version with a simplified version of v2 that also check every layer of a
RelabelType node.

Checking every layer seems reasonable to me. Independently of that, I
believe I've identified a regression caused by the patch: in
exprs_known_equal(), RelabelType is stripped from 'expr' but not from
item1 and item2. A few lines later, 'equal(item1, expr)' and
'equal(item2, expr)' are performed. If item1 or item2 is a RelabelType,
these comparisons now return false.

This can happen when the code is called from have_partkey_equi_join() on
a partitioned table. item1/item2 come from rel->partexprs, and for an
expression partition key like '((c)::text)' on a varchar column, the
stored partition expression is itself a RelabelType node.

I could reproduce the issue as follows. On master, the query plan below
is a partition-wise nested loop; after applying this patch, the plan no
longer contains a partition-wise join:

SET enable_partitionwise_join = on;

CREATE TABLE pb1 (a int, c varchar(40)) PARTITION BY HASH ((c::text));
CREATE TABLE pb1_p0 PARTITION OF pb1 FOR VALUES WITH (MODULUS 2,
REMAINDER 0);
CREATE TABLE pb1_p1 PARTITION OF pb1 FOR VALUES WITH (MODULUS 2,
REMAINDER 1);

CREATE TABLE pb2 (a int, c varchar(40)) PARTITION BY HASH ((c::text));
CREATE TABLE pb2_p0 PARTITION OF pb2 FOR VALUES WITH (MODULUS 2,
REMAINDER 0);
CREATE TABLE pb2_p1 PARTITION OF pb2 FOR VALUES WITH (MODULUS 2,
REMAINDER 1);

-- Master branch
jan=# EXPLAIN (COSTS OFF) SELECT * FROM pb1 JOIN pb2 ON pb1.c::text =
pb2.c::text WHERE pb1.c::text = '0002';
QUERY PLAN
--------------------------------------------------------
Append
-> Nested Loop
-> Seq Scan on pb1_p0 pb1_1
Filter: ((c)::text = '0002'::text)
-> Materialize
-> Seq Scan on pb2_p0 pb2_1
Filter: ((c)::text = '0002'::text)
-> Nested Loop
-> Seq Scan on pb1_p1 pb1_2
Filter: ((c)::text = '0002'::text)
-> Materialize
-> Seq Scan on pb2_p1 pb2_2
Filter: ((c)::text = '0002'::text)
(13 rows)

-- With patch applied
jan=# EXPLAIN (COSTS OFF) SELECT * FROM pb1 JOIN pb2 ON pb1.c::text =
pb2.c::text WHERE pb1.c::text = '0002';
QUERY PLAN
--------------------------------------------------------
Nested Loop
-> Append
-> Seq Scan on pb1_p0 pb1_1
Filter: ((c)::text = '0002'::text)
-> Seq Scan on pb1_p1 pb1_2
Filter: ((c)::text = '0002'::text)
-> Materialize
-> Append
-> Seq Scan on pb2_p0 pb2_1
Filter: ((c)::text = '0002'::text)
-> Seq Scan on pb2_p1 pb2_2
Filter: ((c)::text = '0002'::text)
(12 rows)

I think the RelabelType nodes also need to be stripped from item1/item2
before the comparison. find_ec_member_matching_expr() performs something
similar and the RelabelType is stripped for both arguments of the
equal() call.

Best regards
Jan

--
Jan Nidzwetzki
PlanetScale Postgres Core Team

#7Matheus Alcantara
matheusssilv97@gmail.com
In reply to: Jan Nidzwetzki (#6)
Re: Enable partitionwise join for partition keys wrapped by RelabelType

On Thu Aug 20, 2026 at 10:31 AM -03, Jan Nidzwetzki wrote:

Hello Hackers,

Thanks for the patch, this is a nice planner improvement. The v3 version
applies to the current master branch and check-world passes. I could
also confirm that the provided test case demonstrates the intended
change of the query plan.

Hi Jan,

Thanks a lot for the review and for sharing the regression.

On 27.01.26 16:42, Matheus Alcantara wrote:

I think that unwrapping all Relabel types may ignore intermediate
states. For example, consider Relabel A -> Relabel B -> Base expression:
This code will unwrap Relabel A and Relabel B and check the expression
collation directly on Base expression, shouldn't we check every layer,
e.g Relabel A, Relabel B and Base Expression? Please see the attached v3
version with a simplified version of v2 that also check every layer of a
RelabelType node.

Checking every layer seems reasonable to me. Independently of that, I
believe I've identified a regression caused by the patch: in
exprs_known_equal(), RelabelType is stripped from 'expr' but not from
item1 and item2. A few lines later, 'equal(item1, expr)' and
'equal(item2, expr)' are performed. If item1 or item2 is a RelabelType,
these comparisons now return false.

This can happen when the code is called from have_partkey_equi_join() on
a partitioned table. item1/item2 come from rel->partexprs, and for an
expression partition key like '((c)::text)' on a varchar column, the
stored partition expression is itself a RelabelType node.

I could reproduce the issue as follows. On master, the query plan below
is a partition-wise nested loop; after applying this patch, the plan no
longer contains a partition-wise join:

[ ... ]

I think the RelabelType nodes also need to be stripped from item1/item2
before the comparison. find_ec_member_matching_expr() performs something
similar and the RelabelType is stripped for both arguments of the
equal() call.

Best regards
Jan

You're right, exprs_known_equal() was stripping the RelabelType only
from the EC member's expression, but not from item1/item2. item1/item2
in the have_partkey_equi_join() path come directly from rel->partexprs,
which for an expression partition key like ((c::text)) on a varchar
column are themselves RelabelType-wrapped, so the raw equal() check
happened to succeed by accident (both sides kept the wrapper). Once
em_expr got stripped and item1/item2 didn't, that symmetry broke, and I
could reproduce the regression you reported. Thanks.

The attached v4 patch strips RelabelType from item1 and item2 as well,
so both sides of the equal() check are treated consistently.

While debbuging this down I found a second, related issue: partition
pruning has the same asymmetry. match_clause_to_partition_key() in
partprune.c strips RelabelType from the clause's operands but never from
the partition key expression itself, so for the same class of
RelabelType-wrapped expression keys, pruning silently fails to eliminate
any partitions at all. That's actually what was behind an odd behavior
I ran into while testing your case with data loaded: without
pruning, all partitions stay in the Append, and at small/empty-table row
counts the planner's cost estimate for the partitionwise nested loop and
the non-partitionwise one are close enough that either can be chosen,
which made it look like the join fix wasn't reliable. With pruning fixed
too, pb1.c::text = '0002' now correctly prunes to a single partition on
each side regardless of scale, so the ambiguity goes away entirely. v4
includes that fix as well.

--
Matheus Alcantara
EDB: https://www.enterprisedb.com

Attachments:

t52900_7
v4-0001-Enable-partitionwise-join-for-partition-keys-wrap.patchtext/plain; charset=utf-8; name=v4-0001-Enable-partitionwise-join-for-partition-keys-wrap.patchDownload+184-3
#8Jan Nidzwetzki
jan@planetscale.com
In reply to: Matheus Alcantara (#7)
Re: Enable partitionwise join for partition keys wrapped by RelabelType

Hello Matheus,

On 24.08.26 19:04, Matheus Alcantara wrote:
[...]

You're right, exprs_known_equal() was stripping the RelabelType only
from the EC member's expression, but not from item1/item2. item1/item2
in the have_partkey_equi_join() path come directly from rel->partexprs,
which for an expression partition key like ((c::text)) on a varchar
column are themselves RelabelType-wrapped, so the raw equal() check
happened to succeed by accident (both sides kept the wrapper). Once
em_expr got stripped and item1/item2 didn't, that symmetry broke, and I
could reproduce the regression you reported. Thanks.

[...]

The attached v4 patch strips RelabelType from item1 and item2 as well,
so both sides of the equal() check are treated consistently.

While debbuging this down I found a second, related issue: partition
pruning has the same asymmetry.

Thank you for the updated version 4 of the patch. I can confirm it
applies cleanly to master (5e1e32c2), check-world passes, and the
regression observed in v3 is gone. I looked into the patch and I have
the following comments:

=========
Partprune
=========

The new change in partprune.c might be something that deserves its own
patch since it touches the partitioning code; it's a good improvement,
and it is testable on its own (and not covered by tests so far).

The improvement is easy to demonstrate:

CREATE TABLE vprune (c varchar(40)) PARTITION BY LIST ((c::text));
CREATE TABLE vprune_a PARTITION OF vprune FOR VALUES IN ('a');
CREATE TABLE vprune_b PARTITION OF vprune FOR VALUES IN ('b');

On master
=========
jan=# EXPLAIN (COSTS OFF) SELECT * FROM vprune WHERE c = 'a';
QUERY PLAN
-----------------------------------------
Append
-> Seq Scan on vprune_a vprune_1
Filter: ((c)::text = 'a'::text)
-> Seq Scan on vprune_b vprune_2
Filter: ((c)::text = 'a'::text)
(5 rows)

With the partprune.c part of the patch applied
===============================================
jan=# EXPLAIN (COSTS OFF) SELECT * FROM vprune WHERE c = 'a';
QUERY PLAN
-----------------------------------
Seq Scan on vprune_a vprune
Filter: ((c)::text = 'a'::text)
(2 rows)

===============
Remaining Patch
===============

The new test in partition_join.sql addresses the v3 regression, but it
does not cover the behavior this patch changes: as you note above, with
an expression partition key like ((c::text)), both sides keep the
wrapper. So, the test produces identical output whether the patch is
applied or not.

The mismatch the patch fixes requires exactly one side decorated. That
happens with a plain varchar column key, PARTITION BY HASH (c), where
rel->partexprs holds a plain Var while the equivalence class member is
RelabelType-wrapped.

Making that visible requires two more things: (1) the equality has to
come from the equivalence class rather than from the join clause, so a
constant is required; and (2) the constant must not be prunable at plan
time, otherwise both sides collapse to a single partition. The function
current_setting() satisfies both.

With pht3 and pht4 redefined in this manner (PARTITION BY HASH (c)),
there is no partition-wise join on the master branch for the following
query. However, with the patch applied, this changes:

On master
=========
jan=# SET enable_partitionwise_join = on;
jan=# EXPLAIN (COSTS OFF) SELECT t1.a, t2.a FROM pht3 t1 JOIN pht4 t2
ON t1.c = t2.c WHERE t1.c = current_setting('timezone');
QUERY PLAN

-----------------------------------------------------------------------------
Nested Loop
-> Append
Subplans Removed: 2
-> Seq Scan on pht3_p3 t1_1
Filter: ((c)::text = current_setting('timezone'::text))
-> Materialize
-> Append
Subplans Removed: 2
-> Seq Scan on pht4_p3 t2_1
Filter: ((c)::text = current_setting('timezone'::text))
(10 rows)

With the patch applied
======================
jan=# SET enable_partitionwise_join = on;
jan=# EXPLAIN (COSTS OFF) SELECT t1.a, t2.a FROM pht3 t1 JOIN pht4 t2
ON t1.c = t2.c WHERE t1.c = current_setting('timezone');
QUERY PLAN
-----------------------------------------------------------------------
Append
-> Nested Loop
-> Seq Scan on pht3_p1 t1_1
Filter: ((c)::text = current_setting('timezone'::text))
-> Seq Scan on pht4_p1 t2_1
Filter: ((c)::text = current_setting('timezone'::text))
-> Nested Loop
-> Seq Scan on pht3_p2 t1_2
Filter: ((c)::text = current_setting('timezone'::text))
-> Seq Scan on pht4_p2 t2_2
Filter: ((c)::text = current_setting('timezone'::text))
-> Nested Loop
-> Seq Scan on pht3_p3 t1_3
Filter: ((c)::text = current_setting('timezone'::text))
-> Seq Scan on pht4_p3 t2_3
Filter: ((c)::text = current_setting('timezone'::text))
(16 rows)

I think this would make a good test for partition_join.sql, since it
fails without the patch.

However, the new plan is not necessarily faster than the old one. On
master, both Appends can use run-time pruning (Subplans Removed: 2), so
only one partition per side is scanned. The partition-wise plan lacks
any pruning, so the outer side of every child join is fully scanned.
This seems to be because the pruning information is built from
rel->baserestrictinfo (see create_append_plan()), which is NIL for the
joinrel that a partition-wise Append sits on (see build_join_rel()).
However, plan-time pruning is not affected.

I don't believe the patch is to blame here. The planner opts for the
partition-wise plan based on estimated costs, but these cost estimates
do not account for run-time pruning. As a result, it fails to recognize
that the other plan would eliminate two-thirds of the scans during
execution. The patch simply makes partition-wise joins available for
more queries.

Additionally, the query in question is somewhat artificial, designed to
highlight the EC path; with a simple constant, the partitions are pruned
at planning time regardless. However, enabling partition-wise joins for
these EC-derived equalities could negatively impact queries that
previously benefited from run-time pruning. Was this interaction taken
into account?

================
Further comments
================

1) I couldn't find a test case that proves we need the collation guard
in the introduced strip_collation_preserving_relabel() function. Do you
have a test case that would break without the guard?

2) I am wondering if the following cast in
match_clause_to_partition_key() is actually needed, since
RelabelType.arg is already an (Expr *):

partkey = (const Expr *) ((const RelabelType *) partkey)->arg;

Apart from that, the patch looks good to me.

Best regards
Jan

--
Jan Nidzwetzki
PlanetScale Postgres Core Team

#9Matheus Alcantara
matheusssilv97@gmail.com
In reply to: Jan Nidzwetzki (#8)
Re: Enable partitionwise join for partition keys wrapped by RelabelType

Thanks for the review. v5 is attached, now split into two patches: 0001 is
the partprune fix and 0002 is the exprs_known_equal() fix.

On Tue Aug 25, 2026 at 11:50 AM -03, Jan Nidzwetzki wrote:

The new change in partprune.c might be something that deserves its own
patch since it touches the partitioning code; it's a good improvement,
and it is testable on its own (and not covered by tests so far).

Agreed, it's now 0001 with its own tests in partition_prune.sql. I
covered the three clause shapes the change affects: equality, IN-list
and IS NULL.

The new test in partition_join.sql addresses the v3 regression, but it
does not cover the behavior this patch changes: as you note above, with
an expression partition key like ((c::text)), both sides keep the
wrapper. So, the test produces identical output whether the patch is
applied or not.
[...]
I think this would make a good test for partition_join.sql, since it
fails without the patch.

Yes, you're right, thanks for catching this.

I used a slightly different test case with the same idea, mainly because
current_setting() isn't used anywhere else in partition_join.sql, so I'm
not sure if it could cause issues when running on buildfarm. pht3 and
pht4 are now hashed on (c, d), c is compared to a literal on both sides
so that its equality comes from the equivalence class, and d is joined
normally. Since hash pruning requires every partition key column to be
constrained, constraining only c prunes nothing, so all partitions
survive on both sides.

I confirmed that the new test fails without 0002. With the stripping
removed, the plan collapses to a Nested Loop over two Appends and
partition_join fails.

However, the new plan is not necessarily faster than the old one.
[...]
I don't believe the patch is to blame here.
[...]
However, enabling partition-wise joins for these EC-derived equalities
could negatively impact queries that previously benefited from run-time
pruning. Was this interaction taken into account?

Yes, and I don't think the patch is the responsible here. Your analysis
seems correct to me. create_append_plan() builds the prunequal from
rel->baserestrictinfo, and build_join_rel() sets
joinrel->baserestrictinfo = NIL, so a partitionwise-join Append can
never carry run-time pruning. Worth adding that run-time pruning is
never costed either: part_prune_index is only set during plan creation,
after the cheapest path has already been chosen, and there's no cost
discount for it anywhere in costsize.c or pathnode.c. So both candidates
are costed as though they scan every partition, and the pruned plan's
real advantage is invisible to the comparison.

But that predates this patch since with a plain text partition key the
patch is a no-op, there's no RelabelType anywhere, so
exprs_known_equal() behaves exactly as before, and master already
prefers the partitionwise plan for your query shape, already giving up
run-time pruning. So it doesn't seem to me that the patch introduce any
hazard.

Teaching the cost model about run-time pruning, or letting partitionwise
Appends prune can be a way to improve this, but I'm not sure.

1) I couldn't find a test case that proves we need the collation guard
in the introduced strip_collation_preserving_relabel() function. Do you
have a test case that would break without the guard?

It's hard to reach because have_partkey_equi_join()'s own collation
check compares the partition key expression's collation against
partcollation -- it never learns the collation of the equivalence class
that proved the equality, since exprs_known_equal() returns only a
boolean and discards ec->ec_collation. So the partition key collation
has to equal the column's collation, with only the EC's collation
differing. That arises naturally: canonicalize_ec_expression()
deliberately wraps every EC member in a collation-changing RelabelType
so that it exposes the class's collation.

Under a non-deterministic collation the partitions are then not
join-closed, so a partitionwise join drops matching rows. I confirmed by
deleting the guard and rerunning the suite: the query returns 5 instead
of 9.

Note this tests the guard rather than the patch as a whole, so it also
passes on master, which doesn't strip at all. And only the em_expr side
is covered since I couldn't construct a partexpr carrying a top-level
collation-changing RelabelType, so the item1/item2 side is defensive
only.

2) I am wondering if the following cast in
match_clause_to_partition_key() is actually needed, since
RelabelType.arg is already an (Expr *):

partkey = (const Expr *) ((const RelabelType *) partkey)->arg;

Right, the outer cast is redundant. Removed. Only the inner (const
RelabelType *) cast remains.

--
Matheus Alcantara
EDB: https://www.enterprisedb.com

Attachments:

t52900_9
v5-0001-Fix-partition-pruning-for-partition-keys-wrapped-.patchtext/plain; charset=utf-8; name=v5-0001-Fix-partition-pruning-for-partition-keys-wrapped-.patchDownload+78-1
v5-0002-Enable-partitionwise-join-for-partition-keys-wrap.patchtext/plain; charset=utf-8; name=v5-0002-Enable-partitionwise-join-for-partition-keys-wrap.patchDownload+256-3
#10Jan Nidzwetzki
jan@planetscale.com
In reply to: Matheus Alcantara (#9)
Re: Enable partitionwise join for partition keys wrapped by RelabelType

Hello Matheus,

On 27.08.26 19:08, Matheus Alcantara wrote:

Thanks for the review. v5 is attached, now split into two patches: 0001 is
the partprune fix and 0002 is the exprs_known_equal() fix.

Thank you for the updated, split version 5 of the patch. Both patches
apply cleanly to the main branch (de56594), and I verified that only the
added tests fail when the change is not applied. So, the split and the
tests look good to me. I also appreciate the tests added to
'collate.icu.utf8.sql'.

While testing the patch, I noticed an asymmetry between inner and outer
joins. The patch handles the inner join case, while the outer join case
produces a non-partitionwise query plan.

From my understanding, outer-join clauses don't form an equivalence
class. So, have_partkey_equi_join() can only prove the keys equal by
matching the join clause through match_expr_to_partition_keys(), which
strips the clause operand but compares it against rel->partexprs unstripped.

This can be reproduced as follows:

CREATE TABLE e1 (a int, c varchar(40)) PARTITION BY HASH ((c::text));
CREATE TABLE e1_p1 PARTITION OF e1 FOR VALUES WITH (MODULUS 2, REMAINDER 0);
CREATE TABLE e1_p2 PARTITION OF e1 FOR VALUES WITH (MODULUS 2, REMAINDER 1);
CREATE TABLE e2 (a int, c varchar(40)) PARTITION BY HASH ((c::text));
CREATE TABLE e2_p1 PARTITION OF e2 FOR VALUES WITH (MODULUS 2, REMAINDER 0);
CREATE TABLE e2_p2 PARTITION OF e2 FOR VALUES WITH (MODULUS 2, REMAINDER 1);

SET max_parallel_workers_per_gather = 0;
SET enable_hashjoin = off;
SET enable_mergejoin = off;
SET enable_partitionwise_join = on;

-- inner join: partitionwise
jan=# EXPLAIN (COSTS OFF) SELECT * FROM e1 JOIN e2 ON e1.c::text =
e2.c::text;
QUERY PLAN
--------------------------------------------------------
Append
-> Nested Loop
Join Filter: ((e1_1.c)::text = (e2_1.c)::text)
-> Seq Scan on e1_p1 e1_1
-> Materialize
-> Seq Scan on e2_p1 e2_1
-> Nested Loop
Join Filter: ((e1_2.c)::text = (e2_2.c)::text)
-> Seq Scan on e1_p2 e1_2
-> Materialize
-> Seq Scan on e2_p2 e2_2
(11 rows)

-- outer join: not partitionwise
jan=# EXPLAIN (COSTS OFF) SELECT * FROM e1 LEFT JOIN e2 ON e1.c::text =
e2.c::text;
QUERY PLAN
----------------------------------------------
Nested Loop Left Join
Join Filter: ((e1.c)::text = (e2.c)::text)
-> Append
-> Seq Scan on e1_p1 e1_1
-> Seq Scan on e1_p2 e1_2
-> Materialize
-> Append
-> Seq Scan on e2_p1 e2_1
-> Seq Scan on e2_p2 e2_2
(9 rows)

I did a few tests, and I think we need to do the stripping in
match_expr_to_partition_keys() as well. By applying this change, the
query plan changes as follows:

-- Now partitionwise
jan=# EXPLAIN (COSTS OFF) SELECT * FROM e1 LEFT JOIN e2 ON e1.c::text =
e2.c::text;
QUERY PLAN
--------------------------------------------------------
Append
-> Nested Loop Left Join
Join Filter: ((e1_1.c)::text = (e2_1.c)::text)
-> Seq Scan on e1_p1 e1_1
-> Materialize
-> Seq Scan on e2_p1 e2_1
-> Nested Loop Left Join
Join Filter: ((e1_2.c)::text = (e2_2.c)::text)
-> Seq Scan on e1_p2 e1_2
-> Materialize
-> Seq Scan on e2_p2 e2_2
(11 rows)

I drafted a possible fix in my tree, added a test case that fails
without the modification, and exported it as a new patch. Attached is a
new series. Patches 1 and 2 are yours in an unmodified form. Patch 3 is
the new one, which could potentially be squashed into patch 2 if you
find the modification useful.

Best regards
Jan

--
Jan Nidzwetzki
PlanetScale Postgres Core Team

Attachments:

t52900_10
v6-0001-Fix-partition-pruning-for-partition-keys-wrapped-.patchtext/plain; charset=UTF-8; name=v6-0001-Fix-partition-pruning-for-partition-keys-wrapped-.patchDownload+78-1
v6-0002-Enable-partitionwise-join-for-partition-keys-wrap.patchtext/plain; charset=UTF-8; name=v6-0002-Enable-partitionwise-join-for-partition-keys-wrap.patchDownload+256-3
v6-0003-Enable-partitionwise-join-for-outer-joins-on-Rela.patchtext/plain; charset=UTF-8; name=v6-0003-Enable-partitionwise-join-for-outer-joins-on-Rela.patchDownload+86-6
#11Matheus Alcantara
matheusssilv97@gmail.com
In reply to: Jan Nidzwetzki (#10)
Re: Enable partitionwise join for partition keys wrapped by RelabelType

On Fri Aug 28, 2026, Jan Nidzwetzki wrote:

From my understanding, outer-join clauses don't form an equivalence
class. So, have_partkey_equi_join() can only prove the keys equal by
matching the join clause through match_expr_to_partition_keys(), which
strips the clause operand but compares it against rel->partexprs
unstripped.

I think that's right, for a non-degenerate outer-join qual,
distribute_qual_to_rels() sets maybe_equivalence = false , so
process_equivalence() is never called, the comment there gives the
reason, that the two sides may be unequal above the join once one of
them has gone to NULL. So loop 2 has nothing to work with and loop 1 is
the only path, which is exactly where the unstripped partexprs
comparison bites.

Your 0003 patch looks correct to me, I've just made two additions to its
test:

1. The fix strips both rel->partexprs and rel->nullable_partexprs, but a
two-way LEFT JOIN only ever consults the non-nullable list, so half the
change had no coverage. I added a three-way case:

SELECT count(*) FROM (pht5 t1 LEFT JOIN pht6 t2 ON t1.c::text = t2.c::text)
LEFT JOIN pht7 t3 ON t2.c::text = t3.c::text;

Here the upper clause references t2.c, which can only be in the (pht5,
pht6) joinrel's nullable_partexprs, t1.c is the non-nullable entry and
has a different varno. This was fully non-partitionwise before 0003 and
is fully partitionwise after it, so it does cover the nullable half.

2. Every c value was present in both tables, so the LEFT JOIN produced
no null-extended rows at all. I added one key with no match in pht6 and
changed the query to report count(*) and count(t2.a), so the difference
makes the null-extended row visible and the test checks outer join
semantics rather than just the plan shape.

I also set max_parallel_workers_per_gather = 0 for these, since the
three-way query otherwise picked up a Gather and a Parallel Append whose
child order varied.

Patch 3 is the new one, which could potentially be squashed into patch 2
if you find the modification useful.

I've left it separate for now although I think that make sense to
squash it into 0002. Let's see if a committer have any thoughts on this.

While checking whether match_expr_to_partition_keys(), I found one more
case, and I've fixed on 0004. group_by_has_partkey() strips RelabelType
from the grouping expressions but not from the partition key expression.
The effect is that full partitionwise aggregation is never chosen for a
partition key involving a binary-compatible cast, and the plan falls
back to partial aggregation with a finalize step. Both spellings fail,
for slightly different reasons: GROUP BY c compares a bare Var against a
RelabelType, and GROUP BY c::text strips the grouping side to a bare Var
while the partition key side stays wrapped.

v7 attached. 0001 and 0002 remains the same. 0003 is your patch with new
test cases added and 0004 is the new one.

--
Matheus Alcantara
EDB: https://www.enterprisedb.com

Attachments:

t52900_11
v7-0001-Fix-partition-pruning-for-partition-keys-wrapped-.patchtext/plain; charset=utf-8; name=v7-0001-Fix-partition-pruning-for-partition-keys-wrapped-.patchDownload+78-1
v7-0002-Enable-partitionwise-join-for-partition-keys-wrap.patchtext/plain; charset=utf-8; name=v7-0002-Enable-partitionwise-join-for-partition-keys-wrap.patchDownload+256-3
v7-0003-Enable-partitionwise-join-for-outer-joins-on-Rela.patchtext/plain; charset=utf-8; name=v7-0003-Enable-partitionwise-join-for-outer-joins-on-Rela.patchDownload+153-6
v7-0004-Enable-full-partitionwise-aggregate-for-partition.patchtext/plain; charset=utf-8; name=v7-0004-Enable-full-partitionwise-aggregate-for-partition.patchDownload+86-1
#12Jan Nidzwetzki
jan@planetscale.com
In reply to: Matheus Alcantara (#11)
Re: Enable partitionwise join for partition keys wrapped by RelabelType

Hello Matheus,

Thanks for the updated (v7) set of these patches. The set applies
cleanly to master and check-world runs without any failures.

On 31.08.26 20:07, Matheus Alcantara wrote:

Your 0003 patch looks correct to me, I've just made two additions to its
test:

1. The fix strips both rel->partexprs and rel->nullable_partexprs, but a
two-way LEFT JOIN only ever consults the non-nullable list, so half the
change had no coverage. I added a three-way case:

SELECT count(*) FROM (pht5 t1 LEFT JOIN pht6 t2 ON t1.c::text = t2.c::text)
LEFT JOIN pht7 t3 ON t2.c::text = t3.c::text;

Patches 1-3
===========

Your analysis regarding distribute_qual_to_rels() / maybe_equivalence
sounds reasonable to me. Thanks as well for adding more test coverage to
patch 3. I verified the nullable_partexprs point by reverting only that
branch of the strip. The two-way case still passes, while the three-way
case goes fully non-partitionwise. So, the new test covers the half that
mine missed.

I also looked for other places in the same family that might still be
missing the stripping (e.g., RIGHT, SEMI, and ANTI joins), and didn't
find any. So patches 1 to 3 look good to me from my side.

Patch 4
=======

While checking whether match_expr_to_partition_keys(), I found one more
case, and I've fixed on 0004. group_by_has_partkey() strips RelabelType
from the grouping expressions but not from the partition key expression.
The effect is that full partitionwise aggregation is never chosen for a
partition key involving a binary-compatible cast, and the plan falls
back to partial aggregation with a finalize step. Both spellings fail,
for slightly different reasons: GROUP BY c compares a bare Var against a
RelabelType, and GROUP BY c::text strips the grouping side to a bare Var
while the partition key side stays wrapped.

I think I found a problem in patch 4. group_by_has_partkey() has no
opfamily check, so stripping the RelabelType from the partition key side
means the grouping uses the argument type's equality. In contrast, the
partitioning uses the result type's. If the argument type has coarser
equality than the target, a group can span partitions, and full
partitionwise aggregation produces the wrong result.

For example:

CREATE EXTENSION citext;
CREATE TABLE ct (a int, c citext) PARTITION BY LIST ((c::text));
CREATE TABLE ct_1 PARTITION OF ct FOR VALUES IN ('A');
CREATE TABLE ct_2 PARTITION OF ct FOR VALUES IN ('a');
INSERT INTO ct SELECT i, (CASE WHEN i%2=0 THEN 'A' ELSE 'a' END)::citext
FROM generate_series(1,2000) i;
ANALYZE ct;

SET enable_partitionwise_aggregate = on;
SELECT c, count(*) FROM ct GROUP BY c;
c | count
---+-------
A | 1000
a | 1000
(2 rows)

SET enable_partitionwise_aggregate = off;
SELECT c, count(*) FROM ct GROUP BY c;
c | count
---+-------
A | 2000
(1 row)

The partitions split 'A' and 'a' by text equality, while the grouping
merges them by citext equality. I confirmed that patch 4 introduces
this. Reverting only the planner.c change gives the correct result.

So, I think we need to add an opfamily check here.

Version 8
=========

I attached a new version of the patch series. It contains patch 3 with
an improved commit message. When I wrote the old one, I thought we would
merge it. But if it stays separate, it deserves a better message. Apart
from the commit message, patches 1 to 3 are unchanged.

In patch 4, I added an op_in_opfamily() check in group_by_has_partkey().
This check requires the grouping clause's equality operator to be a
member of the partitioning operator family, which mirrors what
have_partkey_equi_join() already does for the clause operator. The
problem I described above is fixed with that change.

What do you think?

Best regards
Jan
--
Jan Nidzwetzki
PlanetScale Postgres Core Team

Attachments:

t52900_12
v8-0001-Fix-partition-pruning-for-partition-keys-wrapped-.patchtext/plain; charset=UTF-8; name=v8-0001-Fix-partition-pruning-for-partition-keys-wrapped-.patchDownload+78-1
v8-0002-Enable-partitionwise-join-for-partition-keys-wrap.patchtext/plain; charset=UTF-8; name=v8-0002-Enable-partitionwise-join-for-partition-keys-wrap.patchDownload+256-3
v8-0003-Enable-partitionwise-join-for-outer-joins-on-Rela.patchtext/plain; charset=UTF-8; name=v8-0003-Enable-partitionwise-join-for-outer-joins-on-Rela.patchDownload+153-6
v8-0004-Enable-full-partitionwise-aggregate-for-partition.patchtext/plain; charset=UTF-8; name=v8-0004-Enable-full-partitionwise-aggregate-for-partition.patchDownload+168-2
#13Matheus Alcantara
matheusssilv97@gmail.com
In reply to: Jan Nidzwetzki (#12)
Re: Enable partitionwise join for partition keys wrapped by RelabelType

On Tue Sep 1, 2026 at 11:01 AM -03, Jan Nidzwetzki wrote:

I think I found a problem in patch 4. group_by_has_partkey() has no
opfamily check, so stripping the RelabelType from the partition key side
means the grouping uses the argument type's equality. In contrast, the
partitioning uses the result type's.

You're right, and thanks for catching it.

My reasoning when I wrote that patch was that the collation was still
validated separately, which is true but beside the point: collation is
only one dimension of equality semantics, and the type's operator family
is the other. Before the strip, requiring the two expressions to be
structurally equal implicitly guaranteed they had the same type and
therefore the same equality semantics. Stripping the RelabelType removed
that guarantee without replacing it.

In patch 4, I added an op_in_opfamily() check in group_by_has_partkey().
[...]
What do you think?

I think it's right, the citext case now plans as partial aggregation and
returns the correct single group. So v8 looks good to me.

--
Matheus Alcantara
EDB: https://www.enterprisedb.com

#14Jan Nidzwetzki
jan@planetscale.com
In reply to: Matheus Alcantara (#13)
Re: Enable partitionwise join for partition keys wrapped by RelabelType

Hello Matheus,

On 01.09.26 21:37, Matheus Alcantara wrote:

I think it's right, the citext case now plans as partial aggregation and
returns the correct single group. So v8 looks good to me.

Thank you for reviewing and confirming. I ran additional tests on v8 and
found no further issues. The patch series looks good to me as well.

Best regards
Jan

--
Jan Nidzwetzki
PlanetScale Postgres Core Team

#15Jan Nidzwetzki
jan@planetscale.com
In reply to: Jan Nidzwetzki (#14)
Re: Enable partitionwise join for partition keys wrapped by RelabelType

Hello Matheus,

On 01.09.26 23:20, Jan Nidzwetzki wrote:

On 01.09.26 21:37, Matheus Alcantara wrote:

I think it's right, the citext case now plans as partial aggregation and
returns the correct single group. So v8 looks good to me.

Thank you for reviewing and confirming. I ran additional tests on v8 and
found no further issues. The patch series looks good to me as well.

Sorry for the extra round. I noticed that v8 does not pass the tests on
all platforms. The partition bounds 'A' and 'a' in the test I added sort
differently depending on the collation, which changes the order of the
Append children on macOS and Windows. Since the test type compares
case-insensitively, it also changes which of the two values is reported
for the group.

Attached is v9. It adds COLLATE "C" to the partition key of that test,
so the partition order is stable everywhere. This is a test-only change;
no code changed, and patches 1 to 3 are unmodified.

Best regards
Jan

--
Jan Nidzwetzki
PlanetScale Postgres Core Team

Attachments:

t52900_15
v9-0001-Fix-partition-pruning-for-partition-keys-wrapped-.patchtext/plain; charset=UTF-8; name=v9-0001-Fix-partition-pruning-for-partition-keys-wrapped-.patchDownload+78-1
v9-0002-Enable-partitionwise-join-for-partition-keys-wrap.patchtext/plain; charset=UTF-8; name=v9-0002-Enable-partitionwise-join-for-partition-keys-wrap.patchDownload+256-3
v9-0003-Enable-partitionwise-join-for-outer-joins-on-Rela.patchtext/plain; charset=UTF-8; name=v9-0003-Enable-partitionwise-join-for-outer-joins-on-Rela.patchDownload+153-6
v9-0004-Enable-full-partitionwise-aggregate-for-partition.patchtext/plain; charset=UTF-8; name=v9-0004-Enable-full-partitionwise-aggregate-for-partition.patchDownload+168-2
#16Matheus Alcantara
matheusssilv97@gmail.com
In reply to: Jan Nidzwetzki (#15)
Re: Enable partitionwise join for partition keys wrapped by RelabelType

On 01/09/26 19:47, Jan Nidzwetzki wrote:

Hello Matheus,

On 01.09.26 23:20, Jan Nidzwetzki wrote:

On 01.09.26 21:37, Matheus Alcantara wrote:

I think it's right, the citext case now plans as partial aggregation and
returns the correct single group. So v8 looks good to me.

Thank you for reviewing and confirming. I ran additional tests on v8 and
found no further issues. The patch series looks good to me as well.

Sorry for the extra round. I noticed that v8 does not pass the tests on
all platforms. The partition bounds 'A' and 'a' in the test I added sort
differently depending on the collation, which changes the order of the
Append children on macOS and Windows. Since the test type compares
case-insensitively, it also changes which of the two values is reported
for the group.

Attached is v9. It adds COLLATE "C" to the partition key of that test,
so the partition order is stable everywhere. This is a test-only change;
no code changed, and patches 1 to 3 are unmodified.

Thank you for the new patch version. It looks good to me.

I'll mark the CF entry to Ready for committer since the current state
of the review. I can move back to Needs review if more comments shows
up.

--
Matheus Alcantara
EDB: https://www.enterprisedb.com

#17solai v
solai.cdac@gmail.com
In reply to: Matheus Alcantara (#16)
Re: Enable partitionwise join for partition keys wrapped by RelabelType

Hi,

I tested the v9 patch series for partition pruning and partition wise
optimizations involving partition keys wrapped by `RelabelType` on
PostgreSQL.
I applied all four patches in sequence and performed testing for each
of the changes.
My testing observations are as follows:
1. Partition pruning (v9-0001)
Before applying the patch, the EXPLAIN output showed an Append node
with sequential scans on both vprune_a and vprune_b, even though the
query was filtering for 'a'.
After applying the patch, the plan showed only a sequential scan on
vprune_a, excluding the unnecessary partition.
2. Partition Wise inner join (v9-0002)
I tested an inner join between two partitioned tables with varchar
partition keys wrapped in '::text'.
The execution plan showed separate Hash Join operations for the
corresponding partitions ('rel_a_1' with 'rel_b_1', and 'rel_a_2' with
'rel_b_2').
3. Partition Wise outer join (v9-0003)
I tested a 'LEFT JOIN' between the same partitioned tables. After
rebuilding and restarting the server, the execution plan showed an
'Append' node containing separate 'Hash Left Join' operations for the
corresponding partitions.
4. Full partition wise aggregation (v9-0004)

I tested 'GROUP BY' with 'COUNT(*)' on the partitioned table. The
execution plan showed separate 'HashAggregate' nodes for the
individual partitions under an 'Append ' node.
All regression tests passed.
Based on these test cases, the execution plans showed the expected
behavior for partition pruning, partition wise inner joins, outer
joins, and aggregation.

Please let me know if any additional test cases or verification would
be helpful.

Regards
solai