I think that you answered your question - you need to make a transaction block. In PostgreSQL, this should work:
BEGIN;
SET CONSTRAINTS ALL DEFERRED;
INSERT INTO questions (questionid, answerid, question)
VALUES (1, 100, 'How long are Abraham Lincoln\ legs?');
INSERT INTO answers (answerid, questionid, answer)
VALUES (100, 1, 'Long enough to reach the ground.');
COMMIT;
It must be in the transaction block, because if the INSERT statement fails, the database will be in an invalid state (table restrictions are not met).
source
share