MHN

Ask HN: Do you use foreign keys in relational databases?

188 points by frogcoder·1546 days ago·Show in HN

I use foreign keys quite often in my schemas because of data integrity, while my colleague has a no FK policy. His main argument is difficulties during data migrations which he frequently encounters. He rather have a smooth data migration process than having an unexpected error and abort the whole operation that the migration is only a small part of. I suspect the errors might be mainly caused by not considering data integrity at all at the first place, but I can feel his pain. To be fair, as far as I know, he never had major data problems.

He is not the only one I've met who insisted on not having FK. I've even seen large systems prohibit using JOIN statements.

Personally, I see the data integrity out weights the inconveniences, do you use FK for your systems, what are your experiences?

Add a comment on Hacker News →
1 of 244 comments
  1. There are many reasons to not use foreign keys, but it also depends on the kind of application. For small databases, foreign keys do make things simpler from a validation standpoint.

    When building systems for scale where the databases may grow large, foreign keys can cause many issues -

    • ORM features around foreign keys can easily bring your system down when joining large tables with incorrect/missing indexes during heavy loads
    • As the table grows, not having foreign keys makes it simple in taking out large tables into big-data solutions in the future
    • The schemas and relations are sometimes hard to understand during the initial phases of application development. Not having those relations makes changing schemas simpler and faster.
    • Sharding tables is much simpler when there are no foreign keys
    • It helps to add some of the reference logic in the application rather than the database. Databases are the bottlenecks when it comes to IOPS and scaling. The more processing you move to your application server, the better scalability you can achieve.