I have a Postgres 9.2 server with the following table:
Table A
with a single column code
and a B-tree index on it:
db=> \d A
Table "public.A"
Column | Type | Modifiers
--------+--------+-----------
code | bigint | not null
Indexes:
"A_pkey" PRIMARY KEY, btree (code)
I have a simple PLPGSQL function as follows, simplified for ease of following:
create or replace function list (bigint)
RETURNS bigint[] AS '
DECLARE
arr bigint[];
c ALIAS FOR $1;
begin
arr[0] = c * 1;
arr[1] = c * 2;
...
...
arr[10] = c * 1024;
return arr;
END;
' language plpgsql;
I notice that the index is not used if invoke the function:
db => explain select * from A where code = ANY(list(3234234234));
QUERY PLAN
------------------------------------------------------------------------
Seq Scan on A (cost=0.00..1440291398.32 rows=10 width=219)
Filter: (code = ANY (list(3234234234::bigint)))
No luck even if I typecast the output of the function to be ANY(list(3234234234) :: bigint[])
Of course, if I manually create a list it works perfectly.
db=> explain select * from A where code = ANY( '{21312,13123,1312312,1231312,123213231}' :: bigint[]);
QUERY PLAN
----------------------------------------------------------------------------------------
Bitmap Heap Scan on A (cost=538.09..558.17 rows=5 width=219)
Recheck Cond: (code = ANY ('{21312,13123,1312312,1231312,123213231}'::bigint[]))
-> Bitmap Index Scan on A_pkey (cost=0.00..538.09 rows=5 width=0)
Index Cond: (code = ANY ('{21312,13123,1312312,1231312,123213231}'::bigint[]))
Why does Postgres do a sequential scan when using the function?
How do I get it to do index scan with the function?