| From: | Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us> | 
|---|---|
| To: | henning(dot)garus(at)gmail(dot)com | 
| Cc: | pgsql-general(at)lists(dot)postgresql(dot)org | 
| Subject: | Re: Index usage with differing string types | 
| Date: | 2025-02-04 16:34:17 | 
| Message-ID: | 646661.1738686857@sss.pgh.pa.us | 
| Views: | Whole Thread | Raw Message | Download mbox | Resend email | 
| Thread: | |
| Lists: | pgsql-general | 
Henning Garus <henning(dot)garus(at)gmail(dot)com> writes:
> However when the String is cast to text the index isn't used:
> explain select * from test where id = 'foo'::text;
That's because "text" is considered a preferred type, so it wins
the contest over whether '=' means texteq or bpchareq:
# explain select * from test where id = 'foo'::varchar;
                                 QUERY PLAN                                 
----------------------------------------------------------------------------
 Index Only Scan using test_pkey on test  (cost=0.15..8.17 rows=1 width=12)
   Index Cond: (id = 'foo'::bpchar)
(2 rows)
# explain select * from test where id = 'foo'::text;
                      QUERY PLAN                       
-------------------------------------------------------
 Seq Scan on test  (cost=0.00..40.60 rows=10 width=12)
   Filter: ((id)::text = 'foo'::text)
(2 rows)
Your index supports bpchar comparison semantics, not text,
so it doesn't work for this query.
You could work around this by creating an index on id::text,
but TBH I'd question the choice to use a bpchar column in
the first place.  It's pretty much the poster child for
dubious legacy datatypes.
regards, tom lane
| From | Date | Subject | |
|---|---|---|---|
| Next Message | Karsten Hilbert | 2025-02-04 16:51:14 | Re: Lookup tables | 
| Previous Message | Michał Kłeczek | 2025-02-04 16:31:13 | Re: Lookup tables |