I am new to postgres and i'm am having to populate a database using it. I cant submit my actual code for reference but my program is in java and i'm trying to do something along these lines.
IF EXISTS (SELECT 1 FROM TEST WHERE FOO = 2 and BAR = 3)
BEGIN
SELECT TableID FROM TEST WHERE FOO = 2 and BAR = 3
END
ELSE
BEGIN
INSERT INTO TEST(FOO, BAR) VALUES(2, 3)
END
I'm trying to do something along these lines because my program is just parsing a bunch of files and populating the database. I need to ensure that if someone goes back and runs the program again on the same files that the database wont contain duplicate entries. The id associated with this insert/record found is used to populate a linking table. I found this example on another stackoverflow questions only it relates to Microsoft SQL Server 2005. I'm using postgres and it fails on the very first line at IF. I understand different database languages operate slightly different. Is there a way to do an IF EXISTS return ID else insert using postgres.
Currently i'm checking if the entry exist and if it doesnt insert. But then i'm having to query the database again to get the id of the record had it existed.
int id = 0;
PrepareStatement ps = conn.prepare(SQL command, statement.generatekeys); //syntax is not correct for the preparestatement but i'm not looking at my code and dont remember it off top of my head.
ResultSet rs = ps.executeUpdate();
if(rs.next()){
if(rs.getGeneratedKeys().rows() > 0) //not sitting at my code but there is a way to check if a key was generated from an insert
id = rs.getGeneratedKeys()
}else{
id = rs.getInt(1);
}
}
Update Taken from comments:
The better questions is Is there a way to do an if exist return id else insert without querying/checking a where clause twice.
I want to avoid doing a WHERE
check twice to get either my id from existing data or from the new entry. My condition checks are rather lengthy as some of my tables contain upwards of 14 attributes. Currently what i do is query the database once doing an INSERT
if doesn't exist. If my getGeneratedKeys().size() = 0
i know the INSERT
failed because it exist and then I re-query the database with the same where clause from my original query and grab the id.