Re: any way to make query use index? - Mailing list pgsql-admin

From Tom Lane
Subject Re: any way to make query use index?
Date
Msg-id 3669.1195143924@sss.pgh.pa.us
Whole thread Raw
In response to any way to make query use index?  ("Chris Hoover" <revoohc@gmail.com>)
Responses Re: any way to make query use index?  ("Chris Hoover" <revoohc@gmail.com>)
List pgsql-admin
"Chris Hoover" <revoohc@gmail.com> writes:
> SELECT rev_desc FROM rev_code_desc WHERE rev_code = lpad('0300', 4, '0')

> Is there anyway to make postgres use an index on this query?

> Here is the table definition:
> CREATE TABLE rev_code_desc
> (
>   rev_code character(4) NOT NULL,

Since rev_code is char(n), you need to cast the other thing to char(n)
as well:

SELECT rev_desc FROM rev_code_desc WHERE rev_code = lpad('0300', 4, '0')::char(4)

lpad() is declared to return text, which means that your original query
resolves as ... WHERE rev_code::text = lpad('0300', 4, '0'), which
means that the index on rev_code is useless (since it has bpchar
semantics not text semantics).

If changing the queries seems impractical, you could add an index on
rev_code::text, or reconsider the choice of column type.

            regards, tom lane

pgsql-admin by date:

Previous
From: "Tomeh, Husam"
Date:
Subject: Re: Error: duplicate key violates unique constraint - "pg_toast_3270368541_index
Next
From: "Chris Hoover"
Date:
Subject: Re: any way to make query use index?