Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.94.2) (envelope-from ) id 1tfLsU-001iY4-Tf for pgsql-general@arkaria.postgresql.org; Tue, 04 Feb 2025 16:34:23 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.94.2) (envelope-from ) id 1tfLsU-005OPW-0t for pgsql-general@arkaria.postgresql.org; Tue, 04 Feb 2025 16:34:22 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.94.2) (envelope-from ) id 1tfLsT-005OOk-MO for pgsql-general@lists.postgresql.org; Tue, 04 Feb 2025 16:34:21 +0000 Received: from sss.pgh.pa.us ([68.162.161.243]) by magus.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.96) (envelope-from ) id 1tfLsR-003GR7-05 for pgsql-general@lists.postgresql.org; Tue, 04 Feb 2025 16:34:21 +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 514GYHmI646662; Tue, 4 Feb 2025 11:34:17 -0500 From: Tom Lane To: henning.garus@gmail.com cc: pgsql-general@lists.postgresql.org Subject: Re: Index usage with differing string types In-reply-to: References: Comments: In-reply-to Henning Garus message dated "Tue, 04 Feb 2025 17:23:39 +0100" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <646660.1738686857.1@sss.pgh.pa.us> Date: Tue, 04 Feb 2025 11:34:17 -0500 Message-ID: <646661.1738686857@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk Henning Garus 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