Re: Where col like 'abc%' with PreparedStatement

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Andy Fan <zhihui(dot)fan1213(at)gmail(dot)com>
Cc: pgsql-jdbc(at)lists(dot)postgresql(dot)org
Subject: Re: Where col like 'abc%' with PreparedStatement
Date: 2021-03-22 15:56:06
Message-ID: 574558.1616428566@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-jdbc

Andy Fan <zhihui(dot)fan1213(at)gmail(dot)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

In response to

Responses

Browse pgsql-jdbc by date

  From Date Subject
Next Message Andy Fan 2021-03-23 00:12:32 Re: Where col like 'abc%' with PreparedStatement
Previous Message Andy Fan 2021-03-22 15:52:35 Where col like 'abc%' with PreparedStatement