Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1lOMue-0001eD-0W for pgsql-jdbc@arkaria.postgresql.org; Mon, 22 Mar 2021 15:56:16 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1lOMuc-00035x-ON for pgsql-jdbc@arkaria.postgresql.org; Mon, 22 Mar 2021 15:56:14 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1lOMuc-00035q-Io for pgsql-jdbc@lists.postgresql.org; Mon, 22 Mar 2021 15:56:14 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by magus.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1lOMuW-0002bP-Ds for pgsql-jdbc@lists.postgresql.org; Mon, 22 Mar 2021 15:56:14 +0000 Received: from sss1.sss.pgh.pa.us (localhost [127.0.0.1]) by sss.pgh.pa.us (8.15.2/8.15.2) with ESMTP id 12MFu6P7574559; Mon, 22 Mar 2021 11:56:06 -0400 From: Tom Lane To: Andy Fan cc: pgsql-jdbc@lists.postgresql.org Subject: Re: Where col like 'abc%' with PreparedStatement In-reply-to: References: Comments: In-reply-to Andy Fan message dated "Mon, 22 Mar 2021 23:52:35 +0800" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <574557.1616428566.1@sss.pgh.pa.us> Date: Mon, 22 Mar 2021 11:56:06 -0400 Message-ID: <574558.1616428566@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk Andy Fan 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> 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