Re: Using ANY()

From: Jeff Davis <pgsql(at)j-davis(dot)com>
To: Shakil Shaikh <sshaikh(at)hotmail(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Using ANY()
Date: 2009-06-08 18:02:14
Message-ID: 1244484134.21727.18.camel@monkey-cat.sm.truviso.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Sun, 2009-06-07 at 19:33 +0100, Shakil Shaikh wrote:
> Hi all,
>
> Is it appropriate to use ANY() in a select statement as so?
>
> SELECT * FROM table t WHERE t.id = ANY(ARRAY[1,2,3]);

Yes, that's appropriate. A simpler formulation (for that simple case)
is:

... WHERE t.id IN (1,2,3)

> A less trivial usage of the above would be to pass an array to a simple
> function using it to return a range of arbitrary rows.

I don't know exactly what you mean by that.

> The alternative to
> this would be to (programmatically) call the function multiple times on a
> list of arguments. Some questions:

Generally you don't want to submit multiple queries to answer one
question.

> 1) How does ANY() behave on indexed columns?

It can use an index.

> 2) How does ANY() behave when passed an array with one element?

The same as when passed multiple elements. The planner treats it
differently than just doing "t.id = 1", but it can still use an index.
It appears more likely to use a bitmap index scan plan, and maybe it
can't use a normal index scan in that situation.

> 3) Generally is it better to use ANY on a passed ARRAY, or to just call a
> select multiple times (and aggregate the results)? Is ANY just a glorified
> OR?

Using ANY or IN is generally better. The planner is able to do the index
scan in one pass using ANY or IN; if you use a chain of ORs it does
multiple bitmap scans and ORs the results together.

You should try experimenting a little to find the answers to questions
like this. EXPLAIN and EXPLAIN ANALYZE can tell you a lot.

Regards,
Jeff Davis

In response to

  • Using ANY() at 2009-06-07 18:33:25 from Shakil Shaikh

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Gerhard Wiesinger 2009-06-08 18:09:14 Re: Sum of multiplied deltas
Previous Message Boszormenyi Zoltan 2009-06-08 18:00:24 Re: Any way to bring up a PG instance with corrupted data in it?