Re: Definitive answer: can functions use indexes? - Mailing list pgsql-general

From Tom Lane
Subject Re: Definitive answer: can functions use indexes?
Date
Msg-id 16564.1452123713@sss.pgh.pa.us
Whole thread Raw
In response to Definitive answer: can functions use indexes?  (Seamus Abshere <seamus@abshere.net>)
Responses Re: Definitive answer: can functions use indexes?  (Seamus Abshere <seamus@abshere.net>)
Re: Definitive answer: can functions use indexes?  (Jim Nasby <Jim.Nasby@BlueTreble.com>)
List pgsql-general
Seamus Abshere <seamus@abshere.net> writes:
> I've been using Postgres for years ( :heart: ) and I'm still in doubt
> about this. Would somebody provide an authoritative, definitive,
> narrative answer?

> -> Can a function like `LEFT()` use an index?

To do what?

Since the question makes little sense as stated, I'm going to assume
you mean "can a query like SELECT ... WHERE left(foo, 3) = 'bar'
use an index on column foo?"

The answer to that is no, there is no such optimization built into
Postgres.  (In principle there could be, but I've not heard enough
requests to make me think we'd ever pursue it.)

The equivalent optimization that *is* built in, and has been for
a long time, is for LIKE: "SELECT ... WHERE foo LIKE 'bar%'" can
use an index on foo, at least if it's an index sorted according to
C collation.

Another answer, which might serve as long as your application only
cares about a small number of prefix lengths, is functional indexes.
If you create a functional index on "left(foo,3)" you're all set.
This won't scale well to a whole bunch of different lengths, though.

            regards, tom lane


pgsql-general by date:

Previous
From: "Joshua D. Drake"
Date:
Subject: Re: Code of Conduct: Is it time?
Next
From: Seamus Abshere
Date:
Subject: Re: Definitive answer: can functions use indexes?