0

Hi I am trying to do the following in a postgreSql table but am having trouble with the syntax.

Psuedocode:

if (tableA.column1 does not contain value1)
{
    INSERT INTO tableA (column1, column2)
    VALUES value1, value2
}

// do this check even if the above already existed
if (tableB does not contain value1 and value3 in the same row)
{
    // it is ok if value1 and value3 already exist in the table, just not the same row
    INSERT INTO tableB (column1, column2)
    VALUES (value1, value3)
}

return true

Any help with the actual syntax for this operation would be much appreciated!

2
  • I don't see how the first and the second condition "belong" together. You can simply run both independently from each other. Commented Mar 22, 2013 at 14:12
  • interesting, now that i look at it, you make a good point! Commented Mar 22, 2013 at 14:16

1 Answer 1

2
-- first insert:
insert into tablea (col1, col2)
select 1,2
from tablea
where not exists (select * from tablea where col1 = 1);

-- second insert (same logic to apply a conditional insert)
insert into tableb (col1, col2)
select 1,2
from tableb
where not exists (select * from tableb where col1 = 1 and col2 = 2);
Sign up to request clarification or add additional context in comments.

3 Comments

Just remember to LOCK the tables or be prepared to handle errors (if unique) or duplicates (if not unique) due to multiple transactions concurrently checking and inserting the same record.
@CraigRinger: why locking? Isn't simply wrapping into one transaction enough?
@mvp If you know nobody else will be concurrently inserting, yes. But if you know that you know it won't cost you anything to lock either. Inserts don't block each other. If there's a unique key shared between two concurrent inserts then both will SELECT and see the key doesn't exist then both will try to insert it. One will win, the other will fail to commit with a duplicate key error despite not being able to see the conflicting row. If there isn't a unique key then visibility rules will result in neither seeing the row the other is inserting and two rows getting inserted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.