Re: Function to either return one or all records

From: "Tambet Matiisen" <t(dot)matiisen(at)aprote(dot)ee>
To: KÖPFERL Robert <robert(dot)koepferl(at)sonorys(dot)at>, <pgsql-sql(at)postgresql(dot)org>
Subject: Re: Function to either return one or all records
Date: 2005-04-20 20:02:53
Message-ID: A66A11DBF5525341AEF6B8DE39CDE770088073@black.aprote.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

>
> CREATE OR REPLACE FUNCTION getval(integer)
> RETURNS SETOF id_val_tbl AS
> $BODY$
> select * from id_bal_tbl where ( $1 is null )or (id=$1 ); $BODY$
> LANGUAGE 'sql' VOLATILE SECURITY DEFINER;
>
>
> It works fine, however an index is never used (if just one
> record is requested). The column id has a btree-Index but
> what aobut it. I'm wondering how this comes and how one can
> overcome this limit.

The reason why the query worked as plain query may come from the fact that NULL IS NULL was evaluated to constant FALSE and optimized out from OR. In case of function the query was planned before substituting parameters, so the OR was still there and prevented index scan.

Standard technique is to rewrite OR queries to UNION queries. I believe PostgreSQL optimizer does not do that automatically. So you could try instead:

select * from id_bal_tbl where $1 is null
union all
select * from id_bal_tbl where id = $1;

(Note: in general you would need UNION without ALL, to keep the semantics of OR.)

Tambet

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Tom Lane 2005-04-20 21:06:16 Re: Function to either return one or all records
Previous Message Franco Bruno Borghesi 2005-04-20 17:35:56 Re: Query question