Basically I want to assign the result of a query to a custom type attribute. However I noticed that querying directly from the PostgreSQL console was about 0.071 ms and inside the function was 0.400 ms and 0.170 ms after a few calls. explain analyze even shows the usage of indexes in the first case but not on the second.
Here's what I'm doing.
CREATE OR REPLACE FUNCTION fun_isliked(
par_client client.id%type,
par_feed feed.id%type
)
RETURNS boolean
AS
$$
BEGIN
RETURN (
EXISTS(
SELECT
1
FROM
feedlike fl
WHERE
fl.client = par_client
AND fl.feed = par_feed
AND fl.state = 1
)
);
END;
$$ LANGUAGE plpgsql STABLE;
Here are the outputs of explain analyze of the two cases described above:
postgres=# explain analyze select exists (select 1 from feedlike where client = 13 and feed = 68 and state = 1);
QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------------------
Result (cost=8.30..8.31 rows=1 width=0) (actual time=0.037..0.037 rows=1 loops=1)
InitPlan 1 (returns $0)
-> Index Scan using feedlike_client_feed_unique on feedlike (cost=0.28..8.30 rows=1 width=0) (actual time=0.034..0.034 rows=1 loops=1)
Index Cond: ((client = 13) AND (feed = 68))
Filter: (state = 1)
Total runtime: 0.086 ms
postgres=# explain analyze select * from fun_isliked(13, 68);
QUERY PLAN
----------------------------------------------------------------------------------------------------------
Function Scan on fun_isliked (cost=0.25..0.26 rows=1 width=1) (actual time=0.398..0.398 rows=1 loops=1)
Total runtime: 0.416 ms
What is a possible workaround in order to effectively get same runtime inside the function? Is it even possible? Also, I'm running PostgreSQL 9.3.
I found that this question in SO had what I needed but after I tried everything in the selected answer and had no success on reducing the runtime I decided to ask a new question.
explain analyzeresult(s), please. – Craig Ringer Feb 06 '14 at 12:44explain analyzeinside the function? I wonder if the query is being executed differently in that context. – Colin 't Hart Feb 06 '14 at 13:20explain analyzeon the query inside the function yields the same runtime as running it directly in the console, i.e. ~0.70 ms. – oxfist Feb 06 '14 at 13:33EXECUTEbut the runtime didn't drop as I expected. – oxfist Feb 06 '14 at 13:39explain analyzethe function containing theexplain analyze, do you still get a lot of overhead? – Colin 't Hart Feb 06 '14 at 13:58