Database FK Constraints vs Programmatic FK Constraints

前端 未结 3 584
既然无缘
既然无缘 2021-01-24 19:00

Although I am targeting MySQL/PHP, for the sake of my questions, I\'d like to just apply this generally to any relational database that is being used in conjunction with a moder

3条回答
  •  梦谈多话
    2021-01-24 19:44

    What are the pros and cons of creating FK constraints in the database itself as opposed to managing them at the application level?

    Some of the pros of using db-enforced FKs:

    1. Separation of schmea from code.

    2. Making application code smaller

    3. No chance for programmer to mess with FK rules.

    4. Forces other applications that integrate with the db to follow the fk rules.

    Some of the cons of having db-enforced FKs.

    1. Not easy to break if you have a special case

    2. If data is not valid, errors could be thrown. Application should be coded to gracefully handle errors such as those (specially batch ones).

    3. Definition of FK with Referential integrity rules must be defined and coded carefully. You don't want to cascade delete 1000000 rows online.

    4. They cause an implicit check, even if you don't want that check to occur because you know the parent row must exist. This has probably a trivial impact on performance. Performance is an issue when loading huge data volumes in batch loads and in OLAP/Data Warehouse systems. Special load tools are used and constraints such as database enforced FKs are usually disabled during the load.

    From a design standpoint, should they ever both be used together or would that cause conflict?

    You could use them together for a reason. As I mentioned before, you may have special cases in your data that you can't define FKs for. Also, there are certain cases such as many-to-many self referencing relationships between tables that could not be handled by FKs (for some db engines at least).

提交回复
热议问题