Lurker News
I'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

ganonm5 replies#
I'd highly recommend reading SQL Antipatterns. It's a very approachable book that illustrates how to design a database schema by taking commonly encountered scenarios and first showing you the naive approach. After explaining why this is bad, it then shows you the recommended way of doing it and why this way works better.

I think 'learning from how not to do something' is a really powerful pedagogical technique that should be more widespread.

leetrout3 replies#
I tried that in a class I taught. The students were very frustrated and considered it a waste of time.

I agree it’s a FANTASTIC way to learn. I was very disheartened I didn’t effectively communicate that to the students.

hnrodey#
Just a guess, your students probably didn't have the frame of reference or perspective to appreciate good design nor bad design.

Someone who's been in the trenches for several years, they'd probably get A LOT out of this technique as they would have many experiences to pull from.

dspillett3 replies#
Beginners often lack the experience to appreciate "critical thinking" based learning. At first they just want (need?) to know the steps to get something right, especially when they are still not particularly fluent in the very basics.

Once you've got some experience (which usually means getting things wrong a few times, seeing wrongness promoted to production because there isn't time to refactor, and having to fix the wrongness later once more layers or wrong are piled on top) you appreciate this sort of analysis much more as it helps you get things right first time more often, and/or helps you spot the actual problem (rather than chasing symptoms) in more complex situations.

firethief#
It's like humans have to learn how to extract features before they can make efficient use of straightforward supervised learning...
Adutude#
Also the "right" way often changes, in technology, and if you only learned the "right" way, when a better way comes out, you'll miss it because you only ever learned the "right" way and it's all you know.
sitkack2 replies#
> Beginners often lack the experience to appreciate "critical thinking" based learning.

I don't think that is it. _Beginners_ being the critical word.
Most learning is part of a negative feedback loop, if we only ever succeeded we wouldn't know why we succeeded, failure has such bad connotations in our society that it blinds students from deeply understanding a subject. Maybe replace it with experience?
Back to the subject of _Beginners_, we really should be teaching students from a very young age, philosophy, cognitive science, and epistemology. They should embrace experience, it shouldn't be up to the database schema instructor to teach both data modeling and learning by failure. Students should be fully versed in how to care and feed their brains by the time they arrive in the GPs class.

Continue this thread — 2 replies

joshka#
In a work related context recently, I saw this approach used to attempt to describe how to achieve something. The problem for me was that I didn't understand the context well enough to understand why I'd initially even choose the wrong approach, let alone how that then related to choosing the correct approach. Making sure that the fundamentals are important here.
LessDmesg#
I've started reading, and already the second anti-pattern, "Naive trees", is something I've been dealing with at work recently. Hey, how'd he know?!? Cool book.
dspillett1 reply#
> SQL Antipatterns

I'd definitely second that recommendation, both for relative beginners and those of us who have been at it long enough to have learned and forgotten these things a few times over...
https://pragprog.com/book/bksqla/sql-antipatterns or your favourite [e]book seller, for those wanting a copy.
> why this is bad, it then shows you the recommended way of doing it and why this way works better
He also takes the time to mention when the anti-pattern might be OK to use.

contingencies3 replies#
SQL Antipatterns

Saw this thread and just acquired and read this. The book's premise is a great one, I just don't like the execution. Years of my life were dedicated to SQL CRUD and schema evolution before dabbled briefly in NoSQL (meh), random caching systems, then had my aha moment and upgraded to files on unix (awesome caching! great compatibility!) and occasional use of SQLite (easy backup and parallelism! no RDBMS master/slave complexity!).
While there are a few core issues raised, and all struck a chord, I was not a huge fan of the book overall because it was needlessly verbose. I found its authoritative tone grating. Ultimately with so many dialects and projects, SQL style is personal, organizational or project level preference. One issue I felt was undertreated was clarity of syntax. For example, I personally absolutely loathe any use of JOIN as needlessly obtuse cognitive baggage. An untreated issue was (over/mis)use of stored procedures.

jakearmitage1 reply#
How the hell do you deal with locks properly on files? Or each file is a row?

Continue this thread — 1 reply

madno#
Your approach sounds sensible! Do you have some blog posts, pointers which further explains the approach and factors to consider?
triangleman#
I'm sorry can you help me understand how to stop using Join? Some examples or articles on the subject? I can't wrap my head around such a concept.
crtlaltdel#
THANK YOU!!!! This is a fantastic reference, and helps me put some teeth behind my instincts when it comes to SQL.
robodale#
Thanks for the SQL Antipatterns book recommendation. Just ordered it.
singingwolfboy3 replies#
PostGraphile [1] is a framework for generating a GraphQL API based on the tables in your database; as a result, good database design is crucial. Graphile Starter [2] is a quickstart project that demonstrates best practices for getting up and running with PostGraphile quickly. In particular, check out the SQL migration file in that project [3]. It demonstrates:

1. Dividing up tables so that one user can have more than one email address
2. Using PostgreSQL’s “row-level security” system to restrict database results based on the logged in user
3. Dividing tables across multiple schemas for additional security
4. SQL comments for documentation
5. SQL functions for common functionality, such as logging in or verifying an email
It’s a fascinating project, and well worth a look!
[1](https://www.graphile.org/postgraphile/)
[2](https://github.com/graphile/starter)
[3](https://github.com/graphile/starter/blob/master/%40app/db/mi...)

pimmen2 replies#
Users having multiple addresses is something I've cursed a lot over. I work in a team that does data analytics for a news publishing company, and our print business is still very important. Unfortunately, in our database over print customers users are basically addresses because you don't really need to know how many people are receiving your paper as a distributor, only where and how many papers. Since it's also been a safe assumption for a century that people share newspapers with each other, market research was done street by street to inform ad buyers of which markets we reached. Many people have more than one home. Some people take out another subscription for a relative.

This mapped very awkwardly to digital subscribers who we had individual data on. We were able to join databases in a way that sort of works through more or less (mostly less) comfortable assumptions. The queries are not pretty.

jacques_chester1 reply#
There's a whole subfield of information science dedicated to basically this exact problem: entity resolution.

Hilariously, it has dozens of names, because it just comes up in so many places for so many people. It appears that "record linkage" is the term that has won the top spot at Wikipedia: https://en.wikipedia.org/wiki/Record_linkage

eska#
Record linkage seems to be unrelated. While OP isn't sure how to segregate and join data, he has perfect joining capability through unique indices.

Record linkage seems to be concerned with joins that aren't guaranteed to be correct because there are no unique keys.

ltbarcly32 replies#
If you are going to auto generate an api for a database, just use SQL. Adding extra steps between you and a database with no encapsulation is just adding extra steps for no reason.

One of the key things you need to do in good database design is to map business verbs to API endpoints in something like a 1-1 way. Having an api endpoint that is essentially "insert this row to the database" is just cargo culting. There is already an API for that, it's called SQL.

markhalonen1 reply#
I'm using Postgraphile in production on 2 real-world projects and it saves me an incredible amount of time. I spend 90%+ of my time on the front-end because the api is all automated.

Postgrahile allows you to rename/disable api endpoints if needed.
Postgraphile rocks. And it's written in modualar Javascript, so I can hack it if I need to. Unlike Hasura.

ltbarcly32 replies#
Im saying it does something that is a bad idea in the first place. You are saying "yea, but it does it with so little effort".

Continue this thread — 2 replies

BenjieGillam2 replies#
It's not generally safe to expose SQL to untrusted clients. For example, PostgreSQL 12.2 was released yesterday and fixed a security issue where `ALTER ... DEPENDS ON EXTENSION` did not have any privilege check whatsoever. SQL is also not at all well suited for the needs of frontend web app developers - just ask Facebook about their experiences with FQL! Using an API that's more ergonomic for the frontend, such as GraphQL, backed by a language which is optimised for the backend, such as SQL, is the best of both worlds.
ltbarcly33 replies#
Yes of course you cant allow uncontrolled sql execution, but an api that just maps to crud operations isn't good either.

Continue this thread — 3 replies

markhalonen#
No idea why Benjie is getting down voted, SQL from a client is a bad idea, and writing billions and billions of CRUD endpoints is soul-draining.

Postgrahile is the best of both worlds, providing a nice GraphQL interface on top of your database.
If you decide you need to write crud endpoints, you have your database still. It's a zero-cost abstraction, which is wild.

nicktrocado921 reply#
>> 2. Using PostgreSQL’s “row-level security” system to restrict database results based on the logged in user

I'm interested in PostGraphile, but i have a question: How do apply permissions when your user table is different from postgres user systems? i only have handful of users that have permissions spaning a lot of tables.
Do i need to create one postgres user for each of my application users?

adventured3 replies#
The Stackoverflow schema is decent. Especially for someone that is a relative amateur to study. It's nothing special or complex, however it's a good example of something that actually works well in practice (and at massive scale). The CRUD-CMS Q&A style lends itself nicely to a basic db schema that is easy to get your head around at a glance.

https://meta.stackexchange.com/questions/2677/database-schem...
https://i.stack.imgur.com/AyIkW.png
19 million questions, 29m answers, 12m users, 10m visits per day, and most of the db action is in less than two dozen tables.

felixyz#
This is the only answer yet that seems to actually answer the question :) Great example!
jaxn1 reply#
Interesting to see the denormalization of user Display names on the most important tables, but not everywhere.
AdrianB11 reply#
Seeing some training sessions on performance tuning that use this database as the example, an educated guess is that it's done on purpose. I saw a few cases where usual rules have to be bent to get functionality, sometimes reality beats the book.
jaxn#
Oh, I'm sure it is on purpose. I have had the same problem before and seeing this example makes me a little more comfortable to denormalize like that.

I'm curious what they do if someone changes their name (though that should be really rare on SO)

noisy_boy1 reply#
Any idea which tool was used to generate the ER diagram?
noisy_boy#
Thank you!
DanielBMarkham3 replies#
A schema is a way of designing data structures such that they are efficiently organized and easy to use.

But that leaves the obvious question: use for what?
Structures, whether it's databases or object graphs, exist for only two reasons: to do stuff and to fit into a pattern of rules you've decided to use beforehand. Without either of those, there is no way to judge a schema. We could talk about generally organizing data. That's set theory and normal forms. But that wasn't your question.
I would design the schema for a three-microservice widely-distributed high-performance application far differently than I would a local checkbook app for my brother. You gotta have more information.
Apologies. I am unable to help.

pc86#
> I would design the schema for a three-microservice widely-distributed high-performance application far differently than I would a local checkbook app for my brother.

I think it might be helpful to expand on what some of those differences are. I think most of us here would be able to come up with at least a satisfactory schema for a local checkbook app. What are the changes you need to make to that type of schema to make it appropriate for a multi-service app, specifically? What about distributed? HP? Are any of these changes in conflict with each other? Etc

HeroOfAges5 replies#
I agree, and I've come to the conclusion that you should avoid designing a database schema until you have some clear understanding about how the application you're persisting data for will be used. The data structures and schemas will practically jump out at you. It seems, at this point in my career, a very obvious thing, and yet I cannot communicate this point of view in a way to my colleagues that will affect change.

Continue this thread — 5 replies

Continue this thread — 1 more reply

Load more comments