Can foreign keys hurt query performance

前端 未结 11 2011
温柔的废话
温柔的废话 2021-02-02 10:55

As I understood from this post, there are some scenarios where foreign keys can improve query performance.

I\'ve heard the opposite claim though, that because of refere

11条回答
  •  耶瑟儿~
    2021-02-02 11:16

    In theory, yes: data writes need to validate the constraints.

    In practice, seldom: unless measured and proved otherwise, you can assume there is no performance impact. Overwhelmingly, performance problems occur due to other problems:

    • bad schema design (missing indexes, bad clustered index choice)
    • contention (blocking), again due to bad schema design (table scans guarantee lock conflicts)
    • bad query design

    On a well designed schema and good queries the cost of constraints will start to show up at very high throughput. When this happens, there are preventive measures.

    My 2c: Never sacrifice correctness constraints for some elusive performance goals. In the very rare case when the constraints are indeed the problem there are measurements to show that's the case, and as the saying goes: if you have to ask how much it costs, you can't afford it. If you have to ask if constraints can be a problem, you can't remove them (no offence intended).

提交回复
热议问题