X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.144]) by svr1.postgresql.org (Postfix) with ESMTP id 0B2C553609 for ; Wed, 20 Apr 2005 17:03:01 -0300 (ADT) Received: from svr1.postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id 28320-02 for ; Wed, 20 Apr 2005 20:02:56 +0000 (GMT) Received: from ns.aprote.ee (ns.aprote.ee [80.235.78.106]) by svr1.postgresql.org (Postfix) with ESMTP id 1BCA9535DB for ; Wed, 20 Apr 2005 17:02:53 -0300 (ADT) Received: Message by Barricade ns.aprote.ee with ESMTP id j3KK4vGV008816 for ; Wed, 20 Apr 2005 23:04:58 +0300 content-class: urn:content-classes:message MIME-Version: 1.0 Content-Type: text/plain; charset="iso-8859-4" Content-Transfer-Encoding: quoted-printable X-MimeOLE: Produced By Microsoft Exchange V6.0.6556.0 Subject: Re: Function to either return one or all records Date: Wed, 20 Apr 2005 23:02:53 +0300 Message-ID: X-MS-Has-Attach: X-MS-TNEF-Correlator: Thread-Topic: Function to either return one or all records Thread-Index: AcVF4/AW5GPNvkboQg+pBVrwZ7bExA== From: "Tambet Matiisen" To: =?iso-8859-4?Q?K=D6PFERL_Robert?= , X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, hits=0.005 tagged_above=0 required=5 tests=AWL X-Spam-Level: X-Archive-Number: 200504/307 X-Sequence-Number: 21200 >=20 > CREATE OR REPLACE FUNCTION getval(integer) > RETURNS SETOF id_val_tbl AS > $BODY$ > select * from id_bal_tbl where ( $1 is null )or (id=3D$1 ); $BODY$ > LANGUAGE 'sql' VOLATILE SECURITY DEFINER; >=20 >=20 > It works fine, however an index is never used (if just one=20 > record is requested). The column id has a btree-Index but=20 > what aobut it. I'm wondering how this comes and how one can=20 > overcome this limit.=20 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 =3D $1; (Note: in general you would need UNION without ALL, to keep the = semantics of OR.) Tambet