So I have recently started working with postgres. And since I cannot perform an "IF else" unless in a function I am curious which is better resources wise and performance wise. 1. Create a function like the following to query the database storing the id. Check the id to see if its null if it is do insert else return the id;
CREATE OR REPLACE FUNCTION getallfoo() RETURN INT AS
$BODY$
DECLARE
id INTEGER := (SELECT id FROM foo where (lots of condition checks 15+);
BEGIN
IF id is null then
INSERT INTO foo(a,b,c,d,e,f) SELECT (1,2,3,4,5,6) RETURNING id INTO id;
return id;
ELSE
RETURN id;
END IF;
END;
$BODY$
Language 'plpgsql';
select * from getallfoo();
Or 2: To first attempt an insert into the database doing something like the following. Followed by querying the database asuming the insert fails. I have a reason for doing the insert first thats not the point of this question. I know most would say to query first then if doesnt exist insert.
INSERT INTO foo (a,b,c,d,e,f, ........, 15+) SELECT (1,2,3,4,5,6, ........., 15+)
WHERE NOT EXIST(SELECT 1 from foo where a=1, b=2, c=3, up to 15);
Since i'm working in java i would just check if rs.getGeneratedKeys() = 0; if the insert fails i would then requery the database for the id;
SELECT id from foo where a=1, b=2, c=3, ect;
So the question is because my condition checks in my query are lengthy is it better to create a function and query the database once. or to just skip the function and query it twice. I am doing these types of inserts on about 50 different tables.
Side question would be can you do create a function in java using a preparedStatement(the above function) ResultSet rs = ps.executeUpdate();