Subject: Index usage with differing string types

From: Henning Garus <[email-masked]>
Date: Tue, 4 Feb 2025 17:23:39 +0100

Hi,

I stumbled upon this behaviour when digging into the performance of some
merge statements generated by hibernate.

Looking at different String types (varchar, text and bpchar) in some cases
an index is used when the index type differs from the type in the query, in
some cases it isn't used.

Given a table with an index on a bpchar column:

create table test (id bpchar(8) primary key);

Both of the following queries use the index:

explain select * from test where id = 'foo'::bpachar(3);
explain select * from test where id = 'foo'::varchar;

However when the String is cast to text the index isn't used:

explain select * from test where id = 'foo'::text;

This behavior seems to be consistent across postgres 12, 16 and 17.

I find it surprising that the cast to varchar behaves differently than the
cast to text, is this intended behaviour?

Cheers
  Henning

---

From: Adrian Klaver <[email-masked]>
Date: Tue, 4 Feb 2025 08:29:06 -0800

On 2/4/25 08:23, Henning Garus wrote:
> Looking at different String types (varchar, text and bpchar) in some 
> cases an index is used when the index type differs from the type in the 
> query, in some cases it isn't used.
> 

The output from EXPLAIN ANALYZE on each of the queries would be useful.

> I find it surprising that the cast to varchar behaves differently than 
> the cast to text, is this intended behaviour?
> 
> Cheers
>    Henning
> 

-- 
Adrian Klaver
[email-masked]