Ask HN: What are some examples of good database schema designs?
437 pointsI've seen many examples of database schemas but don't always recognise a good design over a mediocre or poor design.
This is what I mean by schema (is this a good design?)
https://www.drupal.org/node/1785994
When I read about database schemas with thousands of tables I wonder what kind of problem could possibly require so many tables.
What are good schema examples? And what are some poor examples?
Comments (175) 52 threads
Show all comments
Showing thread 12 of 52
E.g. The description of an item in a sales invoice is the description at the time the contract of sale is made, and must be immortalised as such as a copy of that description.
+1. I maintain a couple of systems that younger-me wrote 15+ years ago. If younger-me had understood this, I could have avoided much re-engineering :)
If your InvoiceItem has no description, and only has a FK to Product to get the description you're going to have a bad time. Once you build a system around a wrong relationship like that, it's very hard to go back and fix the inevitable issue that updating a product changes old sales invoice records.
Continue this thread — 2 replies
We rely strongly on this at my place of work, it really works! Essentially, you just need two tstzrange columns, representing: (1) when the row was a “valid” representation of the key, (2) when the row could have been used to conduct other “transactions”.
With a valid period and a transaction period, you have a history of the values of an object, and the ability to make non-destructive updates to that object.
It’s an essential component of any audit-worthy system, because it empowers you to trivially answer the question “what did our database think John’s 2018/01/01 address was on the day that we mailed him a check on 2017/12/15”?
1. create a "hole" in the current transaction space's valid space (through expirations of records in transaction time, valid time).
2. insert the new version at (transaction_period=(now, inf), valid_period=(effective_date, inf)).
It sounds complicated, and it sometimes is, but in practice most of the hard work (specifically around transaction periods) is performed for you by triggers. Usually you only have to think about valid periods, as a developer, which is easier to wrap your mind around.
The unfortunate thing is that there aren't a lot of very straightforward open source implementations of bitemporal triggers. The ones that exist are mostly designed to be theoretically sound and feature-complete, rather than usable.
At my company, we have our own implementation that has slowly grown over the years. It's about 500 lines of SQL triggers, and maybe 2k lines of library code in Python/Go to make the ergonomics a little bit easier on the developer.
Continue this thread — 5 replies