From: Rob Tester <robtester@gmail.com>
To: pgsql-sql@postgresql.org
Subject: Help with optional parameters
Date: Wed, 16 Aug 2006 20:39:49 -0700
Message-ID: <f5f60fb50608162039g59585cflbf75aebf0a137bc4@mail.gmail.com> (raw)
I have the need to have optional values for a query in a stored procedure
that I am building. (using postgres 8.1.4). This particular query executes
against a huge table (several million rows) and has six optional parameters
that can be sent to the function. If one of the parameters is null then the
parameter doesn't need to be included in the query. Also the values in the
columns that are optional can contain NULL values. One way that will work
(although extremely cumbersome) is to have a switch on the parameters to
execute the correct query:
--This is a sample
IF (a IS NULL AND b IS NULL) THEN
select * from my_table;
ELSEIF (a IS NOT NULL and b IS NULL) THEN
select * from my_table where a=parama;
ELSEIF (a IS NULL and b IS NOT NULL) THEN
select * from my_table where b=paramb;
ELSE
select * from my_table where a=parama AND b=paramb;
ENDIF;
This is extremely bad when you have 6 parameters giving 64 possible queries.
I tried using this (which works) but the planner likes to throw out the
index for the columns because of the OR condition:
select * from my_table WHERE (parama IS NULL OR a=parama) AND (paramb IS
NULL OR b=paramb);
My next thought was to get the planner to think that using indexes would be
a good thing so I did the following:
select * from my_table WHERE a=COALESCE(parama,a) AND b=COALESCE(paramb,b);
That works great unless the column value for a or b IS NULL in which case
NULL<>NULL because it equals NULL.
Then I used the standby: set transform_null_equals to 1
This allows select null=null to return true.
However, I ran into the problem that a=a (when a is a NULL value) still
equals NULL. But a=NULL is true. So it didn't work out.
What is the best way to write a query and get the planner to use indexes
when you have optional parameters and columns that can contain NULL values?
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients using the --to and --cc options:
reply via email
To: pgsql-sql@postgresql.org
Cc: robtester@gmail.com
Subject: Re: Help with optional parameters
In-Reply-To: <f5f60fb50608162039g59585cflbf75aebf0a137bc4@mail.gmail.com>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox