I’m faced with a situation where I have two tables: A and B. B has a foreign key to A.
A has a column “Detailed” which identifies whether or not its children in B require their “Details” section to be filled out.
If I have my lean structure there is no way for me to determine if a record in B needs to have its “Details” section filled out, i.e. not null, without joining to A. Thus, the only way for me to prevent somebody from inserting or updating these records to an invalid state is to have a trigger to join with A and check its “Detailed” column.
My feeling is that constraints are better than triggers, as they are more like facts about data, in addition to filters, whereas triggers are only filters.
I could get by this by duplicating the “Detailed” column in B and then having a check constraint (Detailed = ‘Y’ AND Details IS NOT NULL) OR (Detailed = ‘N’)
Thoughts on the best way to approach this?
All the tools you mentioned (constraints and triggers) are just a way to enforce the data consistency in the database.
Simple business rules, like “always having a reference”, “not having a
NULL” etc are enforceable with the constraints.More complex business rules, like the one you mention here, should be enforced using triggers.
Constraints are not “better” or “worse” than triggers: they are just a shortcut for the rules you need to implement often.
For your task, just implement a trigger.
However, in
Oracle, both constraints and triggers are implemented not in pure set-based way. They are called in a loop for each record affected by aDMLoperation.Most efficient way would be creating a package that would serve as a single entry point to all
DMLagainst your table and check theDetailsin that package.