PostgreSQL functions. Invalid INSERT performance versus raw SQL INSERT

I am trying to make PostgreSQL function to insert data. My query is very simple, when I execute SQL query outside of a function, I have great performance, but when inside a function, the performance is terrible.

When I do this:

EXPLAIN ANALYZE INSERT INTO car (name) VALUES ('test') RETURNING *;

      

I have great performance (execution time: 0.054ms), which is usually just a simple insert query.

But if I go to a function created like this:

CREATE OR REPLACE FUNCTION createCar(_name text) 
RETURNS SETOF car AS $$
    INSERT INTO car (name) VALUES (_name) RETURNING *;
$$ LANGUAGE sql;

      

I am executing the function like this:

EXPLAIN ANALYZE SELECT * FROM createCar('test');

      

And the performance is terrible (e.g. 10x slower, ~ Runtime: 1.126ms). And it's just a simple insert!

For a simple SELECT function going into the 'STABLE' function, the problem is solved, but for insert I can just be in VOLATILE mode because I am modifying the database ...

I may be doing something wrong, thanks for your help!

+3


source to share





All Articles