• the_rutter (9/6/2010)


    Is it valid design for TableA to reference TableB (foreign key) and TableB to reference back to TableA (foreign key)? Or is this circular reference *always* bad?

    In relational theory, it's fine and valid. And it can be useful. So not always bad.

    In actual DBMSs it's often not allowed, or allowed but badly implemented with problems you have to programme around.

    The relational calculus engine has to check foreign key constraints at transaction commit time if you want a system that allows this in its full generality - and many systems can't handle it properly because a foreign key constraint is checked on the individual statement, not on the whole transaction. Some systems therefore ban it alltogether, while others allow it but you have to programme round issues caused by doing the checks too early.

    It's easy in principle to do it "properly" and mostly not terribly inefficient: one algorithm that works is check on each individual statement, if the check fails add the check (with enough information about the rows concerned to allow efficient processing) to a list to be re-evaluated on commit; on commit if any check on the list fails roll back and throw an error, otherwise allow the commit to proceed. In practise this isn't as easy as it sounds.

    Tom