From: Tom Lane <tgl@sss.pgh.pa.us>
To: Andy Fan <zhihui.fan1213@gmail.com>
Cc: pgsql-jdbc@lists.postgresql.org
Subject: Re: Where col like 'abc%' with PreparedStatement
Date: Mon, 22 Mar 2021 11:56:06 -0400
Message-ID: <574558.1616428566@sss.pgh.pa.us> (raw)
In-Reply-To: <CAKU4AWqQ_KCbyJ2aUcdn2qixKuy7NavqzXorW8Soa9C=X3Fh5A@mail.gmail.com>
References: <CAKU4AWqQ_KCbyJ2aUcdn2qixKuy7NavqzXorW8Soa9C=X3Fh5A@mail.gmail.com>
Andy Fan <zhihui.fan1213@gmail.com> writes:
> The real SQL I want to execute is SELECT * FROM t WHERE col like 'abc%';
> This query
> probably can go with IndexScan since it is prefixed with 'abc'. However I
> am confused when I want
> to use PreparedStatement.
> For example:
> List<Map<String, Object>> imap = jdbcTemplate.queryForList("select *
> from tm where a like ?",
> new Object[] {"a" + "%"}
> );
> The parse tree is sent to postgreSQL is "a like ?", server knows nothing
> about if it is prefixed with
> something or not, so probably Index Scan can't be selected. So what the
> user can use the prepared
> Statement and use the IndexScan for the above case?
The plancache's "custom plan vs generic plan" mechanism is meant to
deal with cases like that. It doesn't always get it right, but if
you consistently use actual values like "abc%" then it will notice
that inserting the parameter value produces a significantly better
plan, and do things that way instead of making a generic plan that
doesn't depend on the parameter value.
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 from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-jdbc@postgresql.org
Cc: tgl@sss.pgh.pa.us, zhihui.fan1213@gmail.com
Subject: Re: Where col like 'abc%' with PreparedStatement
In-Reply-To: <574558.1616428566@sss.pgh.pa.us>
References: <CAKU4AWqQ_KCbyJ2aUcdn2qixKuy7NavqzXorW8Soa9C=X3Fh5A@mail.gmail.com> <574558.1616428566@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