Your basic approach sounds. A trigger is a valid solution. It should work, except for 3 problems :
1) naming convention :
We will need to accurately determine the exact definition of the table, but there is evidence. the error message says: has no field "idanswer" is lowercase. Doesn't say "idanswer" - a case of CaMeL. If you create CaMeL case identifiers in Postgres, you must double them everywhere for the rest of your life.
2) Undo insert violation
Raise EXCEPTION instead of friendly NOTICE to actually abort the whole transaction.
Or RETURN NULL instead of RETURN NEW just disable the inserted row without raising an exception and without rolling back.
I would do the first. This will probably fix the error and work:
CREATE FUNCTION trg_answer_insbef_check() RETURNS trigger AS $func$ BEGIN IF (SELECT c.date FROM "Content" c WHERE c.id = NEW. " idAnswer " ) < (SELECT c.date FROM "Content" c WHERE c.id = NEW. " idQuestion " ) THEN RAISE EXCEPTION 'This Answer is an invalid date'; END IF; RETURN NEW; END $func$ LANGUAGE plpgsql;
the right decision is to use legal, lower names and completely eliminate such problems. This includes your failed table names, as well as the column name date , which is a reserved word in standard SQL and should not be used as an identifier - even if Postgres allows it.
CREATE TRIGGER insbef_check BEFORE INSERT ON "Answer" FOR EACH ROW EXECUTE PROCEDURE trg_answer_insbef_check();
You want to abort invalid inserts before doing anything else.
Of course, you will need to make sure that the Content timestamp table cannot be changed or you need more triggers to make sure your conditions are met.
The same goes for fk columns in Answer .
source share