examine_variable ignored CollateExpr
Thread notes
1 note#bug
hackorum-bot#bug
@global #bug
hi.
ComputeIndexAttrs:
src/backend/commands/indexcmds.c, line 1995:
/*
* Strip any top-level COLLATE clause. This ensures that we treat
* "x COLLATE y" and "(x COLLATE y)" alike.
*/
while (IsA(expr, CollateExpr))
expr = (Node *) ((CollateExpr *) expr)->arg;
That means in function examine_variable:
``foreach(ilist, onerel->indexlist)``
we don't need to worry about RelabelType transformed from COLLATE clause.
CreateStatistics does not have special handling for CollateExpr. Query like:
CREATE STATISTICS t_stx1 ON (a collate "C" collate "C" collate "C"
collate "POSIX") FROM t;
the stored statistics expression node will be a nested CollateExpr.
For the above example,
get_relation_info->get_relation_statistics->eval_const_expressions will
transform the nested CollateExpr into one RelabelType node if column "a"
collation is not POSIX.
RelabelType can be from the CollateExpr transformation, as mentioned above. For
statistics, say ndistinct, ``GROUP BY A COLLATE "C"`` can have different results
from ``GROUP BY A COLLATE case_insensitive``.
Therefore in examine_variable, we can not just simple use:
``
while (IsA(basenode, RelabelType))
basenode = (Node *) ((RelabelType *) basenode)->arg;
``
demo:
CREATE TABLE test_stats_ext_coll (a text, b text, c int);
INSERT INTO test_stats_ext_coll SELECT chr(65 + g % 52) FROM
generate_series(1, 500) g;
CREATE STATISTICS test_stats_ext_coll_stx ON (a COLLATE
case_insensitive) FROM test_stats_ext_coll;
ANALYZE test_stats_ext_coll;
SELECT * FROM check_estimated_rows ($$SELECT count(*) FROM
test_stats_ext_coll GROUP BY a COLLATE case_insensitive $$);
with HEAD:
estimated | actual
-----------+--------
52 | 32
with attached PATCH:
estimated | actual
-----------+--------
32 | 32
function check_estimated_rows is in src/test/regress/sql/stats_ext.sql.
While working on this, I wondered whether we could move check_estimated_rows
from stats_ext.sql to test_setup.sql so that it can be reused more broadly.
Original
From: jian he <jian.universality@gmail.com>
Date: 2026-01-13 10:23
To: PostgreSQL-development <pgsql-hackers@postgresql.org>
Subject: examine_variable ignored CollateExpr
hi.ComputeIndexAttrs:
src/backend/commands/indexcmds.c, line 1995:
/*
* Strip any top-level COLLATE clause. This ensures that we treat
* "x COLLATE y" and "(x COLLATE y)" alike.
*/
while (IsA(expr, CollateExpr))
expr = (Node *) ((CollateExpr *) expr)->arg;That means in function examine_variable:
......
hi, jian, hackers
After reviewing the patch and doing some additional tests and debugging,
I have the following observations about examine_variable():
1.The input Node *node has already been processed by eval_const_expressions().
2.After strip_all_phvs_deep() is applied, adjacent RelabelTypes may be created,
either at the top level or within a deeper subtree.
@jian, in your current code, the processing starts only from the leading RelabelType.
Therefore, adjacent RelabelTypes occurring in non-leading positions, including deeper subtrees,
are not effectively stripped. I believe this may affect the expression that is subsequently
used for comparison with index expressions and extended-statistics expressions.
3.Regarding the current master code, I don't think it is reasonable to try to find a Var
by stripping leading adjacent RelabelTypes and then treat the result as equivalent to
a base Var if a match is found. I agree with Jian's observation on this point:
```C
while (IsA(basenode, RelabelType))
basenode = (Node *) ((RelabelType *) basenode)->arg;
```C
4.I also don't think it is reasonable to strip RelabelTypes from both
the index expressions and extended-statistics expressions before comparing them.
For index expressions, I have not yet found a way to construct an index expression
whose top-level node is a RelabelType. If anyone knows how to construct such an
index expression, I would greatly appreciate an example.
5.Based on the above observations, my current understanding is that
we should normalize the expression after stripping PlaceHolderVars, rather than
simply stripping RelabelTypes from the expression before doing the comparisons.
My current proposal is along the following lines:
/*
* eval_const_expressions() should already have stripped adjacent
* RelabelTypes. However, stripping PlaceHolderVars above may have
* brought previously separated RelabelTypes into adjacency, whether
* at the top level or within a deeper subtree. Therefore, run
* eval_const_expressions() again to normalize the expression.
*
* If the leading RelabelType and its underlying argument have the same
* type, typmod, and collation, and the underlying argument is a base Var,
* applyRelabelType() will reduce the RelabelType chain to that base Var.
* Thus, the resulting expression is equivalent to a plain base Var.
*
* Keep the stripped result in save_node rather than modifying the
* original node. The result is used to compare against indexprs and
* extended-statistics expressions, which are also processed by
* eval_const_expressions() and compared using equal().
*/
I have included below the test SQL cases that I have come up with so far.
Some of the scenarios still need to be verified with GDB.
I understand that this functionality is quite important, and I realize that
my current testing is not yet comprehensive enough. There may also be
some misunderstandings or unreasonable assumptions in my analysis.
I would greatly appreciate any feedback, especially counterexamples or
additional test cases that could challenge my current understanding.
I will continue to improve the analysis and tests based on the feedback.
Thanks!
```SQL
drop COLLATION if exists case_insensitive;
CREATE COLLATION if not exists case_insensitive (provider = icu, locale = 'und-u-ks-level2', deterministic = false);
drop table if exists my_table;
CREATE TABLE my_table (name text COLLATE "C", address text COLLATE "case_insensitive");
INSERT INTO my_table SELECT chr(65 + g % 52), chr(65 + g % 52) FROM generate_series(1, 500) g;
--INSERT INTO my_table SELECT 'a','a' FROM generate_series(1, 2) g;
--INSERT INTO my_table SELECT 'A','A' FROM generate_series(1, 2) g;
ANALYZE my_table;
--View the regular statistics
select * from pg_catalog.pg_stats where tablename = 'my_table'\gx
drop index if exists idx_my_table_address_5;
create index idx_my_table_address_5 on my_table(lower(address COLLATE "case_insensitive" COLLATE "C"));
--View the index information. Note that indexprs is stored as a raw parse tree.
select c.relname,i.* from pg_catalog.pg_index i, pg_catalog.pg_class c where i.indexrelid = c.oid and c.relname like 'idx_my_table_%'\gx
analyze my_table;
--v0/v1 both use idx_my_table_address_5
explain analyze select lower(address COLLATE "case_insensitive" COLLATE "C"), count(*)
from my_table group by lower(address COLLATE "case_insensitive" COLLATE "C");
DROP STATISTICS if exists stx_my_table_name_2;
CREATE STATISTICS stx_my_table_name_2 ON (name COLLATE "case_insensitive" COLLATE "C" COLLATE "case_insensitive") FROM my_table;
analyze my_table;
-- View the definition of the extended statistics.Note that stxexprs is stored as a raw parse tree.
select * from pg_catalog.pg_statistic_ext where stxname = 'stx_my_table_name_2'\gx
-- v0 does not use the extended statistics stx_my_table_name_2,
-- but instead uses the regular statistics for column name.
-- v1 uses the extended statistics stx_my_table_name_2.
explain analyze select name COLLATE "case_insensitive", count(*)
from my_table group by name COLLATE "case_insensitive";
explain analyze select name COLLATE "case_insensitive" COLLATE "C" COLLATE "case_insensitive", count(*)
from my_table group by name COLLATE "case_insensitive" COLLATE "C" COLLATE "case_insensitive";
-- In v0, the first call to examine_variable() directly uses the underlying
-- Var and its regular statistics.
-- In v1, the first call to examine_variable() fails to find a match.
-- On the second call, the underlying Var is used to call examine_variable()
-- again, which finds the regular statistics for the underlying Var.
-- This serves as a fallback mechanism.
explain analyze select address COLLATE "POSIX", count(*)
from my_table group by address COLLATE "POSIX";
regards,
--
ZizhuanLiu (X-MAN)
44973863@qq.com
"=?utf-8?B?Wml6aHVhbkxpdSBYLU1BTg==?=" <44973863@qq.com> writes:
My current proposal is along the following lines:
* eval_const_expressions() should already have stripped adjacent
* RelabelTypes. However, stripping PlaceHolderVars above may have
* brought previously separated RelabelTypes into adjacency, whether
* at the top level or within a deeper subtree. Therefore, run
* eval_const_expressions() again to normalize the expression.
That is a ridiculously expensive way to fix this problem.
regards, tom lane
Original
From: Tom Lane <tgl@sss.pgh.pa.us>
Date: 2026-08-16 23:59
To: ZizhuanLiu X-MAN <44973863@qq.com>
Cc: jian he <jian.universality@gmail.com>, PostgreSQL-development <pgsql-hackers@postgresql.org>
Subject: Re: examine_variable ignored CollateExpr"=?utf-8?B?Wml6aHVhbkxpdSBYLU1BTg==?=" <44973863@qq.com> writes:
My current proposal is along the following lines:
* eval_const_expressions() should already have stripped adjacent
* RelabelTypes. However, stripping PlaceHolderVars above may have
* brought previously separated RelabelTypes into adjacency, whether
* at the top level or within a deeper subtree. Therefore, run
* eval_const_expressions() again to normalize the expression.That is a ridiculously expensive way to fix this problem.
regards, tom lane
Hi, Tom
Thank you for the reminder and guidance.
* eval_const_expressions() again to normalize the expression.
That is a ridiculously expensive way to fix this problem.
I understand the concern that calling eval_const_expressions() again can be relatively expensive.
I took another look at this function and also reviewed the related functions around strip_all_phvs_deep().
(To Richard Guo<rguo@postgresql.org>, I’ve specifically CC’d you because you implemented the functions
related to `strip_all_phvs_deep()`.
/messages/by-id/E1va3GH-003FBe-35@gemulon.postgresql.org
)
One reason why eval_const_expressions() can be expensive is that it invokes eval_const_expressions_mutator(),
which may create new nodes with makeNode() or copy existing nodes using copyObject()/memcpy().
As a result, each additional invocation of eval_const_expressions() may introduce considerable memory allocation
and copying overhead.
Based on the related functions around strip_all_phvs_deep() and applyRelabelType(), I implemented an in-place
function specifically for this purpose. It avoids the unnecessary allocation and copying of expression trees while
performing the required normalization, and should therefore be significantly cheaper than calling eval_const_expressions() again.
The following are the test scenarios and SQL I used previously:
(As mentioned earlier, these tests only cover specific scenarios and are not comprehensive.
We may need to add more performance tests as well.)
drop COLLATION if exists case_insensitive;
CREATE COLLATION if not exists case_insensitive (provider = icu, locale = 'und-u-ks-level2', deterministic = false);
drop table if exists my_table;
CREATE TABLE my_table (name text COLLATE "C", address text COLLATE "case_insensitive");
INSERT INTO my_table SELECT chr(65 + g % 52), chr(65 + g % 52) FROM generate_series(1, 500) g;
--INSERT INTO my_table SELECT 'a','a' FROM generate_series(1, 2) g;
--INSERT INTO my_table SELECT 'A','A' FROM generate_series(1, 2) g;
ANALYZE my_table;
--View the regular statistics
select * from pg_catalog.pg_stats where tablename = 'my_table'\gx
drop index if exists idx_my_table_address_5;
create index idx_my_table_address_5 on my_table(lower(address COLLATE "case_insensitive" COLLATE "C"));
--View the index information. Note that indexprs is stored as a raw parse tree.
select c.relname,i.* from pg_catalog.pg_index i, pg_catalog.pg_class c where i.indexrelid = c.oid and c.relname like 'idx_my_table_%'\gx
analyze my_table;
--v0/v3 both use idx_my_table_address_5
explain analyze select lower(address COLLATE "case_insensitive" COLLATE "C"), count(*)
from my_table group by lower(address COLLATE "case_insensitive" COLLATE "C");
DROP STATISTICS if exists stx_my_table_name_2;
CREATE STATISTICS stx_my_table_name_2 ON (name COLLATE "case_insensitive" COLLATE "C" COLLATE "case_insensitive") FROM my_table;
analyze my_table;
-- View the definition of the extended statistics.Note that stxexprs is stored as a raw parse tree.
select * from pg_catalog.pg_statistic_ext where stxname = 'stx_my_table_name_2'\gx
-- v0 does not use the extended statistics stx_my_table_name_2,
-- but instead uses the regular statistics for column name.
-- v3 uses the extended statistics stx_my_table_name_2.
explain analyze select name COLLATE "case_insensitive", count(*)
from my_table group by name COLLATE "case_insensitive";
explain analyze select name COLLATE "case_insensitive" COLLATE "C" COLLATE "case_insensitive", count(*)
from my_table group by name COLLATE "case_insensitive" COLLATE "C" COLLATE "case_insensitive";
-- In v0, the first call to examine_variable() directly uses the underlying
-- Var and its regular statistics.
-- In v3, the first call to examine_variable() fails to find a match.
-- On the second call, the underlying Var is used to call examine_variable()
-- again, which finds the regular statistics for the underlying Var.
-- This serves as a fallback mechanism.
explain analyze select address COLLATE "POSIX", count(*)
from my_table group by address COLLATE "POSIX";
regards,
--
ZizhuanLiu (X-MAN)
44973863@qq.com
Hi hackers,
Upon further consideration, in the newly added function strip_all_adjacency_relabeltypes_walker,
when handling adjacent RelabelType nodes, besides performance and memory space related
optimizations, we should also follow the behavior of applyRelabelType() and perform analogous
processing on the RelabelType’s argument.
The resulting expression yields an equivalent simple Var, which can be used to look up column statistics,
and also works correctly for equal() comparisons against index expressions and extended statistics expressions.
The test SQL and scenarios remain the same as in my previous mail.
regards,
--
ZizhuanLiu (X-MAN)
44973863@qq.com
Hi Jian,
With v1 or v4 I get a worse estimate when the table has no
statistics object.
CREATE TABLE t (a text);
INSERT INTO t SELECT chr(65 + g % 52)
FROM generate_series(1, 5200) g;
ANALYZE t;
EXPLAIN SELECT * FROM t WHERE a COLLATE "C" = 'A';
On master I get
Seq Scan on t (cost=0.00..89.00 rows=100 width=2)
With v1 or v4 I get
Seq Scan on t (cost=0.00..89.00 rows=26 width=2)
Could we keep the stripping, and check the statistics expressions
first only when a COLLATE was stripped from a plain column? A
table without extended statistics pays one test of rel->statlist.
Thanks,
Shihao
Original
From: shihao zhong <zhong950419@gmail.com>
Date: 2026-10-05 11:59
To: ZizhuanLiu X-MAN <44973863@qq.com>
Cc: pgsql-hackers <pgsql-hackers@lists.postgresql.org>, jian he <jian.universality@gmail.com>, tgl <tgl@sss.pgh.pa.us>, Guo <rguo@postgresql.org>
Subject: Re: examine_variable ignored CollateExpr
Hi Jian,With v1 or v4 I get a worse estimate when the table has no
statistics object.CREATE TABLE t (a text);
INSERT INTO t SELECT chr(65 + g % 52)
FROM generate_series(1, 5200) g;
ANALYZE t;
EXPLAIN SELECT * FROM t WHERE a COLLATE "C" = 'A';On master I get
Seq Scan on t (cost=0.00..89.00 rows=100 width=2)
With v1 or v4 I get
Seq Scan on t (cost=0.00..89.00 rows=26 width=2)Could we keep the stripping, and check the statistics expressions
first only when a COLLATE was stripped from a plain column? A
table without extended statistics pays one test of rel->statlist.Thanks,
Shihao
Hi, Shihao
Thank you for your feedback!
Hi, all
Fix RelabelType handling in statistics lookup
Regarding examine_variable() in src/backend/utils/adt/selfuncs.c:
1. Handling adjacent RelabelType nodes after stripping PHVs
PATCH[1]/messages/by-id/E1va3GH-003FBe-35@gemulon.postgresql.org added PHV stripping for node, followed by the following loop on
the resulting basenode:
```C
while (IsA(basenode, RelabelType))
basenode = (Node *) ((RelabelType *) basenode)->arg;
```C
This loop strips only consecutive RelabelType nodes at the top level.
It does not handle adjacent RelabelType nodes that may arise deeper
in the expression tree.
Since stripping PHVs, as introduced by PATCH[1]/messages/by-id/E1va3GH-003FBe-35@gemulon.postgresql.org, can bring previously
separated RelabelType nodes into adjacency, I think it would be better to
strip these adjacent nodes at the point where this adjacency can arise.
This keeps the creation and removal of adjacent RelabelType nodes together
as a single, cohesive operation, without requiring a heavyweight function.
I therefore chose to call the new helper function strip_all_adjacency_relabeltypes()
from within strip_all_phvs_mutator().
(Sorry, my previous version of strip_all_adjacency_relabeltypes()
did not actually return the stripped expression.)
2. Preserving the previous lookup behavior
Before PATCH[1]/messages/by-id/E1va3GH-003FBe-35@gemulon.postgresql.org, there was a symmetric attempt to strip the topmost RelabelType
from the input node, index expressions, and extended statistics expressions
before comparing them. The relevant code is as follows:
```C
--for node
if (IsA(node, RelabelType))
basenode = (Node *) ((RelabelType *) node)->arg;
else
basenode = node;
--for index's expr
if (indexkey && IsA(indexkey, RelabelType))
indexkey = (Node *) ((RelabelType *) indexkey)->arg;
--for extended statistics
if (expr && IsA(expr, RelabelType))
expr = (Node *) ((RelabelType *) expr)->arg;
```C
The original behavior was to strip the topmost RelabelType before comparing
expressions with equal().
However, this is not entirely satisfactory. Ideally, we should use statistics
associated with expressions that match exactly according to equal().
Stripping the topmost RelabelType before comparison should be a fallback
rather than the preferred approach.
Therefore, the new PATCH first compares the input expression, index expressions,
and extended statistics expressions as they are, without stripping their topmost
RelabelType nodes. If no matching statistics are found, it retries the lookup under
certain conditions, symmetrically stripping the topmost RelabelType from the
input expression and the candidate expressions before comparing them.
This preserves the behavior that existed before PATCH[1]/messages/by-id/E1va3GH-003FBe-35@gemulon.postgresql.org as a fallback, maintaining
compatibility with the previous lookup logic.
(The normalization performed by strip_all_phvs_mutator(), following logic similar to
applyRelabelType(), is a separate matter and remains appropriate. It normalizes
adjacent RelabelType nodes that may arise when PHVs are stripped, while preserving
the semantics of the outermost relabeling. This is consistent with the normalization
already applied to index expressions and extended statistics expressions.)
Feedback is welcome.
[1]: /messages/by-id/E1va3GH-003FBe-35@gemulon.postgresql.org
[1]: /messages/by-id/E1va3GH-003FBe-35@gemulon.postgresql.org
The following are the relevant test SQL statements:
1. After strip_all_phvs_mutator() and strip_all_adjacency_relabeltypes(),
statistics are successfully found for the corresponding index expressions
and extended statistics expressions:
--setup
DROP TABLE IF EXISTS phv_left, phv_right CASCADE;
DROP COLLATION IF EXISTS case_insensitive;
CREATE COLLATION case_insensitive
(provider = icu,
locale = 'und-u-ks-level2',
deterministic = false);
CREATE TABLE phv_left ( id int );
CREATE TABLE phv_right( id int, name text COLLATE "C");
INSERT INTO phv_left
SELECT g
FROM generate_series(1, 1100) AS g;
INSERT INTO phv_right
SELECT g,
CASE WHEN g % 17 = 0 THEN NULL
ELSE chr(65 + (g % 26))
END
FROM generate_series(1, 1000) AS g;
-- Matches the statistics for index phv_right_index_5
create index phv_right_index_5 on phv_right(COALESCE(name COLLATE "C", ''::text COLLATE "C"));
analyze phv_right;
EXPLAIN analyze
SELECT r.x COLLATE "C" AS k,
count(*)
FROM phv_left AS l
LEFT JOIN
(
SELECT id,
(COALESCE(name COLLATE "C", ''::text COLLATE "C") COLLATE case_insensitive) AS x
FROM phv_right
) AS r
ON r.id = l.id
GROUP BY r.x COLLATE "C";
-- Matches the statistics for extended statistics object phv_right_expr_stats_5
drop index phv_right_index_5; --drop phv_right_index_5 first
create STATISTICS phv_right_expr_stats_5
on (COALESCE(name COLLATE "C", ''::text COLLATE "C"))
FROM phv_right; ANALYZE phv_right;
analyze phv_right;
EXPLAIN analyze
SELECT r.x COLLATE "C" AS k,
count(*)
FROM phv_left AS l
LEFT JOIN
(
SELECT id,
(COALESCE(name COLLATE "C", ''::text COLLATE "C") COLLATE case_insensitive) AS x
FROM phv_right
) AS r
ON r.id = l.id
GROUP BY r.x COLLATE "C";
2. Statistics for the underlying Var are found after stripping the topmost RelabelType from basenode on the second attempt:
CREATE TABLE t (a text);
INSERT INTO t SELECT chr(65 + g % 52)
FROM generate_series(1, 5200) g;
ANALYZE t;
EXPLAIN SELECT * FROM t WHERE a COLLATE "C" = 'A';
regards,
--
ZizhuanLiu (X-MAN)
44973863@qq.com
Hi Zizhuan,
Thanks for v5. My example is fixed, I get rows=100 again. The
regression tests pass, and I could not measure any change in
planning time for varchar columns.
One more issue
CREATE TABLE t (a text);
INSERT INTO t SELECT chr(65 + g % 52) || g
FROM generate_series(1, 5200) g;
CREATE STATISTICS s ON (left(a, 1) COLLATE "C") FROM t;
ANALYZE t;
EXPLAIN SELECT * FROM t WHERE left(a, 1) = 'A';
On master I get rows=100, with v5 I get rows=26. I think the retry
only runs when the query has the COLLATE, not when only the
statistics expression has it.
v5 also dropped the tests that v1 had. Could you add them back,
with this case and my earlier one?
Thanks,
Shihao
Original
From: shihao zhong <zhong950419@gmail.com>
Date: 2026-10-11 10:38
To: ZizhuanLiu X-MAN <44973863@qq.com>
Cc: pgsql-hackers <pgsql-hackers@lists.postgresql.org>, jian he <jian.universality@gmail.com>, tgl <tgl@sss.pgh.pa.us>, Guo <rguo@postgresql.org>
Subject: Re: examine_variable ignored CollateExprHi Zizhuan,
Thanks for v5. My example is fixed, I get rows=100 again. The
regression tests pass, and I could not measure any change in
planning time for varchar columns.One more issue
CREATE TABLE t (a text);
INSERT INTO t SELECT chr(65 + g % 52) || g
FROM generate_series(1, 5200) g;
CREATE STATISTICS s ON (left(a, 1) COLLATE "C") FROM t;
ANALYZE t;
EXPLAIN SELECT * FROM t WHERE left(a, 1) = 'A';On master I get rows=100, with v5 I get rows=26. I think the retry
only runs when the query has the COLLATE, not when only the
statistics expression has it.v5 also dropped the tests that v1 had. Could you add them back,
with this case and my earlier one?Thanks,
Shihao
Hi, Shihao,hackers
Thank you for your prompt and constructive feedback.
I've updated the code to avoid unnecessary comparisons on retry.
It now separately tracks whether node, indexpr, and statexpr have
a topmost RelabelType associated with COLLATE, and uses these
flags to determine which comparisons are necessary:
- indexpr is compared only if basenode_is_topmost_relabeltype or indexkey_is_topmost_relabeltype is true.
- statexpr is compared only if basenode_is_topmost_relabeltype or statexpr_is_topmost_relabeltype is true.
All the issues you mentioned have been addressed, and the missing test cases have been added.
The corresponding regression tests and expected output have also been updated in the .sql and .out files.
Thanks again for your review and suggestions.
regards,
--
ZizhuanLiu (X-MAN)
44973863@qq.com
Sorry,
there was a mistake in stats_import.out. I've fixed it and updated the patch.
regards,
--
ZizhuanLiu (X-MAN)
44973863@qq.com
Hi Jian, Shihao, hackers,
I have revised the statistics lookup change to prefer exact expression
statistics, while retaining top-level RelabelType stripping as a fallback
when no exact statistics tuple is available. This also addresses the
fallback cases Shihao reported: either the query expression or the
statistics expression can have the top-level relabeling.
This v7 includes the PHV/relabel normalization previously posted as
CF 7730 [1, 2], so it can be applied as one patch to the master base used
for this revision. That normalization has not yet received sufficient
review; I describe its role below.
The motivation is that a RelabelType can carry more than a binary-compatible
type change. It can represent COLLATE, and preserving the same stored
values does not imply preserving their equality semantics or number of
distinct values. Stripping it unconditionally can both hide useful exact
statistics and incorrectly carry uniqueness across a collation or type
change. On the other hand, requiring exact matches everywhere would lose
useful column and expression statistics in cases that worked previously.
There is an important representation difference between the three kinds
of expression involved in examine_variable():
* The input expression and an extended-statistics expression keep COLLATE
in the expression tree. The catalog stores the latter in
pg_statistic_ext.stxexprs. Planner simplification normally represents a
necessary COLLATE as RelabelType, and can eliminate redundant relabels.
Extended expression statistics use exprCollation(expr) when comparing
sampled values, and occupy entries in pg_statistic_ext_data.stxdexpr.
* For an expression index, ComputeIndexAttrs() first obtains the expression's
type and collation, then removes top-level CollateExpr nodes before
storing indexprs. An index-key COLLATE specification can also override
the collation. The effective index collation is recorded separately in
pg_index.indcollation and loaded into rd_indcollation. Binary-compatible
casts can still leave RelabelType nodes in the index expression.
During ANALYZE, the expression in indexprs supplies the sampled values.
examine_attribute() in commands/analyze.c uses the expression's result
type and typmod, and preferentially uses rd_indcollation for comparing
those values, falling back to exprCollation(index_expr) when necessary.
Thus both indexprs and the external collation matter. The external
collation governs result-value comparisons; it does not replace the
collations of operations inside indexprs. Expression-index statistics
are stored in pg_statistic under the index OID and index column number.
A key such as a COLLATE "abc" that reduces to a plain Var is recorded
as an ordinary index column. Statistics lookup for the underlying
table column uses its column statistics, collected under the column's
declared collation. The examples below use genuine expression keys.
The lookup now has two stages.
First, retain top-level RelabelType nodes and look for exact statistics,
with the existing index-before-extended-statistics priority. For extended
statistics, compare the expression trees with equal(). Index matching
also accounts for the external collation:
if (indexcollation == exprCollation(indexkey))
exact_match = equal(node, indexkey);
else
exact_match =
exprCollation(node) == indexcollation &&
exprType(node) == exprType(indexkey) &&
exprTypmod(node) == exprTypmod(indexkey) &&
equal(strip_top_relabel(node), strip_top_relabel(indexkey));
Here strip_top_relabel() is explanatory shorthand for looking through
one top-level RelabelType. The second branch aligns the two storage
representations of the result collation while retaining the type and
typmod checks. Matching collation OIDs are required; separate collation
objects with the same settings are still separate objects for matching.
While searching, record possible fallback candidates and their expression
positions, but defer loading their statistics. If no exact statistics
tuple is found, use column statistics when stripping exposes a simple Var.
Otherwise, try the recorded index candidates, then extended-statistics
candidates, in their original order until usable statistics are found.
Recording multiple candidates allows a later source to supply statistics
when an earlier partial index or statistics object has none. Fallback
comparisons remove top-level relabeling symmetrically. An index can also
be a fallback candidate when neither tree has a RelabelType, because its
external collation can differ from the query's collation.
The comparison expressions have outer-join nulling relids removed in both
stages. The expression returned in vardata retains them. Only exact
index matches can newly establish uniqueness, including an applicable
partial unique index that supplies no whole-table statistics. A fallback
index match only supplies statistics. Ordinary-column uniqueness is
considered when actually falling back to that column, with matching
collation and default equality operator, and is combined with any existing
exact uniqueness information. Fallback therefore remains an approximate
reuse of statistics rather than a new proof of equivalent equality
semantics.
Some examples from the regression tests illustrate these choices. The
SQL excerpts below use the data and setup in the corresponding tests.
1. Exact expression statistics before column fallback
(collate.icu.utf8.sql).
The relabel_stats test has a primary-key text column under "C", with
52 values generated by chr(65 + g), g = 0..51. This particular set has
32 groups under the test's nondeterministic case_insensitive collation.
CREATE STATISTICS relabel_expr
ON (a COLLATE case_insensitive) FROM relabel_stats;
ANALYZE relabel_stats;
EXPLAIN SELECT count(*) FROM relabel_stats
GROUP BY a COLLATE case_insensitive;
With exact expression statistics, the estimate is 32 groups. GROUP BY a
still estimates 52. After DROP STATISTICS relabel_expr, the collated
query falls back to column statistics and estimates 52, while the actual
result still has 32 groups. This deliberately shows the approximation
in fallback and why exact statistics should take precedence. The
column's uniqueness under "C" must not imply uniqueness under the
case-insensitive collation.
2. An index whose result collation is stored outside indexprs
(collate.icu.utf8.sql).
The relabel_index_stats test contains A..Z and a..z, repeated 20 times:
CREATE INDEX relabel_index_ci ON relabel_index_stats
((left(a, 1) COLLATE case_insensitive));
CREATE STATISTICS relabel_index_expr
ON (left(a, 1)) FROM relabel_index_stats;
ANALYZE relabel_index_stats;
EXPLAIN SELECT left(a, 1) FROM relabel_index_stats
GROUP BY left(a, 1);
EXPLAIN SELECT left(a, 1) COLLATE case_insensitive
FROM relabel_index_stats
GROUP BY left(a, 1) COLLATE case_insensitive;
The first query estimates 52 groups using exact extended expression
statistics under "C". The second estimates 26 using the expression
index's statistics under case_insensitive. The stored index expression
is left(a, 1), with its original "C" collation, while indcollation is
case_insensitive. Comparing only indexprs would wrongly accept the
index as an exact match for the first query and fail to recognize the
representation of the second query's exact match.
3. Fallback from either side, and continuing past unavailable statistics
(stats_ext.sql).
For 5,200 rows containing each of 52 initial characters 100 times,
the tests estimate and return 100 rows in each of these cases:
-- Only the statistics expression has top-level COLLATE.
CREATE STATISTICS relabel_expr
ON (left(a, 1) COLLATE "POSIX") FROM relabel_stats;
-- After ANALYZE:
SELECT * FROM relabel_stats WHERE left(a, 1) = 'A';
-- A separate test puts COLLATE only on the query expression,
-- with statistics on the uncollated left(a, 1).
SELECT * FROM relabel_stats
WHERE left(a, 1) COLLATE "POSIX" = 'A';
The plain-column case a COLLATE "POSIX" = 'A', with only column
statistics collected under "C", likewise estimates and returns 100.
Further tests put an unusable partial index or an empty expression-
statistics entry before a usable fallback source. Those still produce
100/100. An exact partial unique expression-index match followed by
column-statistics fallback preserves the 1/1 estimate.
4. Binary compatibility does not make statistics interchangeable
(stats_ext.sql).
With alternating 'A' and 'A ' values, the test creates:
CREATE INDEX relabel_cast_idx ON relabel_cast
((left(a, 3)::pg_catalog.bpchar COLLATE "POSIX"));
CREATE STATISTICS relabel_cast_stats
ON (left(a, 3) COLLATE "POSIX") FROM relabel_cast;
ANALYZE relabel_cast;
EXPLAIN SELECT left(a, 3) COLLATE "POSIX" FROM relabel_cast
GROUP BY left(a, 3) COLLATE "POSIX";
text and bpchar are binary-compatible here, but bpchar ignores trailing
spaces in equality. The text query has two groups and must use the
exact text statistics, rather than treating the bpchar index's one-group
statistics as exact after stripping a relabel. The test estimates and
returns two groups. Related tests ensure that unique text expressions
do not imply unique bpchar results, and distinguish different typmods
when aligning an external collation.
The main additional cost is in planning. Normalization adds checks within
the existing recursive PHV-removal walk; the lightweight PHV-presence
check still avoids that copying walk when no PHVs are present.
Each visited expression during statistics lookup can
require an extra equal() comparison, and matching fallback candidates
allocate list entries for the source and its position. Memory use is
proportional to the number of recorded candidates. A relabeled simple
Var can now search expression indexes and extended statistics before
falling back to column statistics, whereas unconditional stripping used
to reach the column fast path immediately. Exact-match priority can
also require searching farther than accepting the first approximate
match. If exact lookup fails, trying candidates adds catalog/cache or
statistics-hook accesses, including unsuccessful attempts.
The fallback stage visits the recorded candidates, so it avoids another
full expression-list scan and another PHV-stripping pass. Looking through
a top-level relabel uses an existing child pointer. The bare-Var fast
path remains. The implementation also adds review and maintenance work:
the two lookup stages, paired candidate lists, index collation alignment,
and the distinction between statistics reuse and uniqueness inference all
need to stay consistent. I have not measured planning-time overhead for
this revision, so I cannot yet quantify that tradeoff. The patch changes
statistics selection; catalog formats and ANALYZE's collection rules stay
the same.
The included normalization was previously posted as "Normalize RelabelTypes
after stripping PlaceHolderVars", CF 7730 [1]https://commitfest.postgresql.org/patch/7730/, discussed in [2]/messages/by-id/tencent_F3747F5B5B4250CF3542C1C7B5A9D0BE4F0A@qq.com. It
normalizes adjacent or redundant RelabelType nodes that PHV stripping can
expose at any depth, preserving necessary outer relabeling. Together with
the existing planner simplification of index and statistics expressions,
this permits the lookup code to strip a single top-level RelabelType.
CF 7730 is currently Needs review and has not yet received sufficient
review. I originally split it out to make that component easier to
review. This v7 includes it with the lookup change, and its correctness
still needs review as part of this patch.
The PHV/adjacent-relabel tests in join.sql cover the normalization portion.
The exact/fallback lookup tests are in stats_ext.sql and
collate.icu.utf8.sql. The current combined branch passes the debug/assert
build, pgindent --check, git diff --check, and all six relevant regression
tests including setup dependencies: test_setup, create_misc, create_index,
join, stats_ext, and collate.icu.utf8.
I would appreciate feedback on the matching policy and whether the added
planning and maintenance costs are justified by these cases, particularly
the search before falling back to a relabeled simple Var.
[1]: https://commitfest.postgresql.org/patch/7730/
[2]: /messages/by-id/tencent_F3747F5B5B4250CF3542C1C7B5A9D0BE4F0A@qq.com
[3]: Original discussion:/messages/by-id/CACJufxGLCiyhM+P0gxesg2x--PTrMY3PszqSqOq_H4QS_oq3Jg@mail.gmail.com
regards,
--
ZizhuanLiu (X-MAN)
44973863@qq.com
Hi Zizhuan,
Thanks for v7. I think in v7, a varchar column in WHERE is still missed.
CREATE COLLATION ci (provider = icu, locale = 'und-u-ks-level2',
deterministic = false);
CREATE TABLE v (a varchar COLLATE "C");
INSERT INTO v SELECT chr(65 + g % 52) FROM generate_series(1, 5200) g;
CREATE STATISTICS vs ON (a COLLATE ci) FROM v;
ANALYZE v;
EXPLAIN ANALYZE SELECT * FROM v WHERE a COLLATE ci = 'a';
GROUP BY a COLLATE ci uses the statistics. This query still estimates
100 rows for 200 actual, same as master.
Thanks,
Shihao