From: Tom Lane <tgl@sss.pgh.pa.us>
To: Abdullah DURSUN <adursuns@gmail.com>
Cc: pgsql-bugs@lists.postgresql.org
Subject: Re: Planner does not use btree index for LIKE 'prefix%' on text column, but does for equivalent range query (PostgreSQL 17.4)
Date: Sat, 03 May 2025 16:04:14 -0400
Message-ID: <2202693.1746302654@sss.pgh.pa.us> (raw)
In-Reply-To: <CADgr+dF2yaJ88e6i=PU+znW3YX7uir2nL56NpoOzuk87-nk4wg@mail.gmail.com>
References: <CADgr+dF2yaJ88e6i=PU+znW3YX7uir2nL56NpoOzuk87-nk4wg@mail.gmail.com>
Abdullah DURSUN <adursuns@gmail.com> writes:
> A btree index on a text column is not used for a query of the form WHERE
> col LIKE 'prefix%', even though the index is healthy, statistics are
> correct, and the query is highly selective.
LIKE with a prefix condition can only use an index if the index's
collation is "C", or if it uses the "pattern" opclass. This isn't
new in v17, it's been true for a very long time.
d1=# create table foo (t text);
CREATE TABLE
d1=# create index on foo (t);
CREATE INDEX
d1=# explain select * from foo where t like 'prefix%';
QUERY PLAN
-----------------------------------------------------
Seq Scan on foo (cost=0.00..27.00 rows=7 width=32)
Filter: (t ~~ 'prefix%'::text)
(2 rows)
d1=# create index on foo (t collate "C");
CREATE INDEX
d1=# explain select * from foo where t like 'prefix%';
QUERY PLAN
-------------------------------------------------------------------------
Bitmap Heap Scan on foo (cost=4.22..14.37 rows=7 width=32)
Filter: (t ~~ 'prefix%'::text)
-> Bitmap Index Scan on foo_t_idx1 (cost=0.00..4.22 rows=7 width=0)
Index Cond: ((t >= 'prefix'::text) AND (t < 'prefiy'::text))
(4 rows)
regards, tom lane
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients using the --to and --cc options:
reply via email
To: pgsql-bugs@postgresql.org
Cc: tgl@sss.pgh.pa.us, adursuns@gmail.com, pgsql-bugs@lists.postgresql.org
Subject: Re: Planner does not use btree index for LIKE 'prefix%' on text column, but does for equivalent range query (PostgreSQL 17.4)
In-Reply-To: <2202693.1746302654@sss.pgh.pa.us>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox