r/learnSQL • • 17d ago

ID design and composite primary keys, pt. III

I've been writing a series of posts on ID design and primary keys, and just published the third part: https://anchorsandlinks.com/posts/primary-keys-3/. It discusses a well-known pattern of composite primary keys in entity tables. It is relatively rarely used, and the text explains why. This pattern can only be used when several criteria are satisfied, and it may become an obstacle when business requirements change. The rationale for using composite primary keys is that it can give performance improvements in some scenarios.

1 Upvotes

82 comments sorted by

2

u/Ultra-Ferric 17d ago

I took a brief look at your article and I believe you have a fundamental misunderstanding of the relational model.
A Reddit thread can’t fill this gap, but I highly recommend that you begin by reading the works of Chris J. Date, Fabian Pascal, and Joe Celko (to name a few) and avoid perpetuating this unfortunate, yet common misinformation about keys and identifiers.

Here’s a free short article by Celko, one of the members of the SQL 92 advisory committee, that may crack open the hatch for you, and other data practitioners:
https://www.informationweek.com/data-management/celko-on-sql-identifiers-and-the-properties-of-relational-keys

1

u/squadette23 17d ago

Thank you!

What is the first sentence that you find incorrect in the text?

1

u/Ultra-Ferric 17d ago

I commend you for being curious and accepting my comment at face value, instead of being defensive, like most people would probably be 👍

The whole notion that the so called “artificial keys”, or “IDs” which aren’t keys at all, is a diseases that has plagued database design for decades. It actually stems from the pre-relational concept of pointers, which aren’t keys, but are necessary for imperative programming.

It is one of the most devastating factors in destroying data integrity, complicating queries, and consequently degrading performance.

That short article by Celko should get you started in questioning the basis for the common “wisdom” that artificial keys are somehow necessary. The other authors I mentioned should be the next step in your quest for true understanding.

If you are truly passionate and interested in understanding data modeling in general, and the relational model in particular, you have a fascinating journey ahead of you.
Remember that even if 99% of the people around have an opinion about something, doesn’t make it true.
It took rebels like Pythagoras and Aristotle to make the world realize that the earth isn’t flat…

1

u/squadette23 17d ago

That short article by Celko should get you started in questioning the basis for the common “wisdom” that artificial keys are somehow necessary.

Oh, great! Could you share what the SQL schema would be like for the business requirements that are discussed in the text?

Here is a copy for reference:

"Suppose that we build a tiny blog system. Users can create posts and add comments.

One small but important thing: suppose that we want to enumerate comments under the post so that they have a stable identification: sequential numbers starting from 1 in each post. For example, if there are comments #1, #2 and #3, and the second comment is deleted, the third comment still needs to have number 3."

Thank you! It's really hard to discuss this artificial keys-free approach in detail because the discourse is completely swamped by the "industry-standard" approach.

1

u/Ultra-Ferric 17d ago

A comment is a comment, it is not #1, #2, or any number, until you impose a sorting function.
This is why a set, by definition, has no order.

When you say first, second, third, you are likely imposing a chronological order.

The real attribute of the comment is its time stamp.
When you use that to determine which comment should be displayed first, or second, the whole challenge of the “missing second” completely disappears.

1

u/squadette23 17d ago

Okay, thank you. So, it's going to be

CREATE TABLE comments (  
  created_at TIMESTAMP NOT NULL PRIMARY KEY,
  body VARCHAR(1500) NOT NULL  
);

Right?

1

u/Ultra-Ferric 17d ago

The SQL table definition is the last step in a long process… the logical data model needs to be established first.

To your point, I would imagine that a comment would have many more attributes than that, starting with the key of the person who posted it, the key of the post it is assigned to, the IP address, and potentially many more, depending on the subset of the universe you choose to model.

How you identify a person is another rabbit hole.
Could be a username, an email account, an Oauth token, SSN, or any number of real attributes - but never a locally generated “ID”🙂

1

u/squadette23 17d ago

Let's do a trivial teaching exercise, like I asked you to do. In the industry-standard textbook approach it takes 12 meaningful SQL lines, as shown in the article that you say is fundamentally confused.

Let's show what does fundamentally correct version look like, if possible. How long could it take?

Suppose that users have email address (for logging in) and username (so that, as implied by the business requirements, we could generate the URL such as /squadette/314159.html#c23).

We need to be able to build a trivial application that does what the business requirements say.

Your first idea is to use timestamp instead of auto-generated ID.

Would this be correct SQL version?

CREATE TABLE users (
  username VARCHAR(32) NOT NULL PRIMARY KEY
  email VARCHAR(128) NOT NULL,
  UNIQUE (email)
  . . .  
);

CREATE TABLE posts (  
  created_at TIMESTAMP NOT NULL PRIMARY KEY,  
  username VARCHAR(32) NOT NULL,
  FOREIGN KEY (username) REFERENCES users (username)
  body VARCHAR(1500) NOT NULL  
);

CREATE TABLE comments (  
  created_at TIMESTAMP NOT NULL PRIMARY KEY,  
  post_created_at TIMESTAMP NOT NULL,  
  FOREIGN KEY (post_created_at) REFERENCES posts (created_at),
  seq_num INTEGER NOT NULL,  
  username VARCHAR(32) NOT NULL,  
  FOREIGN KEY (username) REFERENCES users (username)
  body VARCHAR(1500) NOT NULL  
);

Thank you,

2

u/Ultra-Ferric 16d ago

I would think the PK of posts should be (username, created_at) as multiple users can post different posts at the same time.
Similarly, comments key will be (username, created_at) and the FK to posts should naturally be composite as well.
What’s the seq-num thing?
If you want to create threads of comments within a post you’ll also need the parent comment composite key.

1

u/squadette23 16d ago

What’s the seq-num thing?

This is the part of business requirements: "One small but important thing: suppose that we want to enumerate comments under the post so that they have a stable identification: sequential numbers starting from 1 in each post. For example, if there are comments #1, #2 and #3, and the second comment is deleted, the third comment still needs to have number 3.""

Basically I, as the user of such a system, need to see if a comment was deleted and there is a gap. Also, I need to have short user-readable identifiers so that I could say "as Chris said in comment #3, we..."

→ More replies

1

u/squadette23 16d ago

I would think the PK of posts should be (username, created_at) as multiple users can post different posts at the same time.

Okay, thank you, makes sense.

My next question would be this. Suppose that we've lived with such a schema for some time, and we've added a lot of functionality such as voting for posts and comments, bookmarking posts, adding images, etc. The usual "content management system stuff". So we have half a dozen additional tables that use (username, created_at) foreign keys in their own schema. That's understandable.

Now we need to implement a feature that is often requested by the users: changing the username. How would you implement this feature? Thank you,

→ More replies

1

u/Lucky_Cable_3145 16d ago edited 16d ago

Comments need to be linked to the parent post, this design does not do that because there is only 1 'username'

There are 2 different users required; the creator of the POST and the creator of the COMMENT

EDIT: THIS STATEMENT IS INCORRECT:Username is not unique so should not be a PK or FK.

→ More replies

1

u/Lucky_Cable_3145 16d ago edited 16d ago

Again, I strongly advise you to NOT use a date time as a primary key or a composite key (unless you have an explicit requirement that forces you to).

No database I have worked on in the last 15 years has used a composite key.

In COMMENTS you need 2 username fields, one for the POST FK and one for the USERS FK

EDIT: Removed an incorrect statement.

1

u/squadette23 17d ago

How you identify a person is another rabbit hole. Could be a username, an email account, an Oauth token, SSN, or any number of real attributes - but never a locally generated “ID”

Basically my question is: in the teaching problem that we discuss, what would be the foreign key definition for the posts.user_id and comments.user_id. They are integers in the confused version of SQL schema, but that's fine, what are their fundamentally correct data types?

2

u/Lucky_Cable_3145 16d ago

Something like this;

CREATE TABLE users (
username VARCHAR(32) NOT NULL PRIMARY KEY
email VARCHAR(128) NOT NULL,
UNIQUE (email)
. . .
);

CREATE TABLE posts (
created_at TIMESTAMP NOT NULL,
username VARCHAR(32) NOT NULL,
FOREIGN KEY (username) REFERENCES users (username).
body VARCHAR(1500) NOT NULL ,
PRIMARY KEY(created_at, username)
);

CREATE TABLE comments (
created_at TIMESTAMP NOT NULL,
username VARCHAR(32) NOT NULL,
post_created_at TIMESTAMP NOT NULL,
post_username VARCHAR(32) NOT NULL,
body VARCHAR(1500) NOT NULL ,
PRIMARY KEY(created_at, username)
FOREIGN KEY (post_created_at, post_username) REFERENCES posts (created_at, username),
FOREIGN KEY (username) REFERENCES users (username)
);

Notice how we need 2 fields for the FK, even in this simple 2 deep hierarchy of POST -> COMMENT.

Imagine the complexity when we get a very deep hierarchy.

Also the performance hit from having to index multiple non numeric data types once we have millions of rows of data

1

u/squadette23 15d ago

The real attribute of the comment is its time stamp.

I have another question about using timestamps as (parts of) primary keys. For comments/posts it's clear that you can use them in principle.

What happens for things like books, or vinyl records? Suppose that we're a used books shop, and we want to build a catalog of books. Not every book has ISBN, obviously. What would you use a PK of "books" table?

1

u/Ultra-Ferric 15d ago

ISBN is the industry standard identifier and I’ve used it in more than one project.
Wherever possible, it should be used.
For older and niche books a possible key would be (author, title, edition) . Some use cases may require more granular key such as print batch, minor revisions , etc.

1

u/squadette23 15d ago

Okay, thank you. I don't understand the part of "some use cases may require more granular key", could you walk me through it?

Suppose that we started with (author, title, edition). We work for a few years, and we build a database of many books. We have lots of tables that refer to the central "books" table: incoming/outgoing orders, favorites, reviews, inventory, etc., etc.

Suddenly a new book arrives that apparently is a "some use case", so we need a more granular key such as (author, title, edition, minor_revision). How specifically would you extend your schema to a new PK (or solve it in a different way)?

Also, what do we, as a business, do until you didn't extend the schema, how can we put the book online, or do we have to wait?

1

u/Ultra-Ferric 15d ago

That doesn’t happen normally.
By “use case” I mean the business data model, which can be different for different types of businesses even for the same item.

The “granularity” is the atomic unit that your model treats as a single , indivisible entity.
The database used by the author likely cares only about the title and revision.
The publisher may treat different translations, paperback vs hardcovers as their own entities, and the printer may further need to track specific print batches.
The library that lends out the books may need to track individual copies.
Each use case determines the model, and consequently the identifiers and keys.

It is highly unlikely that the author suddenly has a new use case where he needs to track individual copies around the world.

1

u/squadette23 14d ago

Okay, thank you. I don't understand the "highly unlikely" part. I'm asking what to do when that happens. Maybe not in the use case of "used books shop", but in other business areas. I don't want to be vague here so I won't press further, because you answered in the "Slack" example.

(author, title, edition)

But I have a question about this. "author" cannot be part of primary key, because books can have many authors, including no authors. So we would need some other disambiguation fields.

I wonder if there is a specific procedure to reliably construct PKs for taxonomically complicated subject matters?

Also, the book titles can be quite long. Apparently, you're fine with keeping a copy of book's title, and the rest of the PK in every child table? Is there any limit to the total length of PK where you should find some other approaches, in your experience?

thank you,

→ More replies

1

u/Lucky_Cable_3145 17d ago

Decades ago I helped to develop a train control system DB that used a composite key; Track ID, Direction, DateTime.

You would assume a section of train track can't have 2 trains on it, going different directions, at the same time.

You would be wrong, because the government implemented daylight saving time...

This is the problem with using a time stamp as a primary key; that it may not be unique.

Things often occur at the 'same' time, depending on the resolution you use (minute, second, millisec, ect).

Timestamps are also relative to location (ie time zone).

Then you get daylight saving when 1 hour can repeat.

My rule is 'real world data will always find a way to break your code', served me well over the decades.

1

u/Ultra-Ferric 17d ago

You’re confusing the timestamp itself with its locality representation.

Ignoring quantum physics for the sake of the practical discussion, a point in time, regardless of any database or any human calling it by a name at any location on the planet, is just that - a zero length point on the time continuum, from the big bang to infinity.

It’s an abstract concept, and us humans have developed a standard way of communicating it, which is UTC.
* side note - the history of UTC and how we got there is fascinating in its own right… see https://youtu.be/mkVxJVgO1QY

Therefore, storing timestamps in a database should always use UTC time which is universal (ignoring quirks like Unix time for this discussion).

Now, you may or may not need to take into account regional variables such as time zones and DST, but that’s completely separate from the actual time stamp itself.
You may want to store the time zone where the event happened as a geographical attribute, and present the time adjusted for that zone.

But that opens up further questions. For example, what happens if I log in to the application from a different continent? What time should I see - the time where the train is, or the time where I am?

These need to be established as part of the application’s requirements and incorporated into the data model, but it doesn’t determine the entity nor its keys.

1

u/Lucky_Cable_3145 17d ago edited 17d ago

Yes, timestamps should always be stored in the DB as UTC, then converted into local time in the UI (based on business rules).

That does not solve the issue of simultaneous events

In this example 2 posters creating a comment at the exact same time. What order do they display in? Probably one based on rowid.

What advantage does the complexity of a composite key give you over the simplicity of a sequence / identity / autonumber? Given a non clustered index will act similar to a clustered index on a composite key.

EDIT: To clarify the 'train control' key.

It was a private railway, operating in a single timezone with no daylight saving.

For a variety of 'good' reasons we incorrectly chose to use local time (ie time syncronisation between multiple IOT devices).

Point is that what appeared a solid design when we created it later failed due to changes outside our control.

1

u/Ultra-Ferric 17d ago

Presentation sorting is completely independent of the underlying events, which are a set, and therefore, by definition, have no order.

If you have 2 posters commenting at the exact same time, and your key is (poster + time), then theoretically they could get the same time stamp, depending on the resolution of the data type that you use - it is unlikely for high resolution types but not impossible.

In that case you can designate an arbitrary tie breaker, or randomly choose either row as “first” and it will still be true.
SQL ORDER BY clause does the same - ORDER BY X provides no guarantees to the order of rows that contain the same value for expression X.

There is no complexity in composite keys. It’s a fact of life derived from the reality and implemented in the model.
It actually simplifies the querying process as there is no abstraction layer between the meaningful data and the query.

For example, if you go to a conference, you get a name badge with your real name on it.
Imagine that instead you’ll get a GUID on the front of the badge , and a “lookup table” on the back for all attendees.
You meet someone and say “Hello there…. Hmmmm …. A12C9667…. One moment… Jim!
Sounds ridiculous , right?
This is exactly what every query that uses an ID instead of a natural key has to go through.

Here’s a 45 minute video of my ex partner-in-crime explaining some of the considerations and consequences of using “artificial keys” in an interesting and fun way.
https://youtu.be/r2MDDPDi_Pg

1

u/Lucky_Cable_3145 17d ago edited 17d ago

Your very simplistic example has a COMMENTS table with 4 fields; PostID, UserID, TimeStamp, CommentText.

First you suggested using PostID, TimeStamp as the composite key.

I pointed out simultaneous events would break that design.

Now you suggest PostID, UserID, TimeStamp as the composite key.

What happens if keeping a history of edits to the comment later becomes a requirement?

Does the composite key become every field in the COMMENT table?

Or do you need to add fields to the composite key? (Edit timestamp + current comment)

Or do you have to replicate the PostID, UserID, TimeStamp fields in the COMMENT_HISTORY table?

Rather than just simply replicating the COMMENTS ID field in the COMMENT_HISTORY table.

→ More replies

1

u/Lucky_Cable_3145 17d ago

Imagine that instead you’ll get a GUID on the front of the badge , and a “lookup table” on the back for all attendees.
You meet someone and say “Hello there…. Hmmmm …. A12C9667…. One moment… Jim!

The name tag it the equivalent of the UI, not the DB data.

The DB 'thinks' in GUIDs, the UI converts the DB 'speak' to what people can easily understand.

→ More replies

1

u/Lucky_Cable_3145 17d ago

Presentation sorting is completely independent of the underlying events, which are a set, and therefore, by definition, have no order.

Events generally are not a set, they are time series data, which by definition has order.

→ More replies

1

u/squadette23 14d ago

by reading the works of Chris J. Date, Fabian Pascal, and Joe Celko

Could you share which chapters of books by Date and Celko specifically contain answers to questions that I've been asking in this thread? I've read my share of Date and I am not satisfied with what it. It either touches the same trivial examples over and over again, or handwaves away the questions that would inevitably arise in practice.

I've read quite a bit of material from Derek Asirvadem, who is also a purist, but unfortunately it also quite often feels like "now draw the rest of the fscking owl".

Thank you,

1

u/squadette23 14d ago

I tried to approach some of Fabian Pascal's stuff, but it seems that it's the same stuff over and over again. I've re-read the tables of contents in his "Practical database foundations" (https://www.dbdebunk.com/p/papers_3.html) and they are written on the wrong level.

I want a specific discussion of how real database tables look, given the business requirements. I'm fine with algebra, but this algebra needs to actionable. Unfortunately, a lot of algebra in relational model rather describes tables post-factum and does not help actually designing them.

1

u/Ultra-Ferric 14d ago

Start with Joe Celko’s “Data and databases”.
It is a much easier read.
There will come a time when Fabian’s work will make more sense.

1

u/squadette23 14d ago edited 14d ago

Okay, I've skimmed the table of contents and some pages and it seems to be the same stuff as usual.

Also, I found the following interesting snippet on page 189:

Surrogate key: Also called a “meaningless key” or “artificial key”; a key constructed inside the database that contains no information in itself. A surrogate key is often used in place of a meaningful compound key that is too unwieldy to use in an actual database.

What do you think about that?

The section "Autoincremented Surrogate Keys" on pages 191-192 is just inane. It says "The serial datatype vendor extensions to SQL have several problems." and then it proceeds with explaining something that is not a problem. I understand that the book was written 27 years ago, but it's just not useful.

Update: I've read "Difficulty of Changing Surrogate Keys", it's just weird. A lot of the books on relational theory keep doing the same shtick: they show you something stupid, and then proudly show you how to not do this stupid thing. It's never clear why would you ever do the original stupid thing to begin with. Also, they often do not tell you how to reliably do the correct thing.

Same here, with this "Zitzi" example.

"In the Zitzi Automobile Company example, too much of the programming logic would depend on having the source of the part within the part number to factor it into a separate nonkey column. In the real world, they would probably expand the size of the part number from four to five or six digits by multiplying the old numbers by 10 or 100 to extend the existing pattern. Yes, this is a bad idea, but this is the way of the world."

I have no idea what this is supposed to teach me.

There will come a time when Fabian’s work will make more sense.

You sound extremely condescending!

But what I meant is that I don't see anything super insightful in Pascal's work, it's the same stuff, maybe a bit more opinionated.

But maybe I am wrong, do you have an example of Pascal's paper that you think is really difficult intellectually?

thank you,

1

u/squadette23 14d ago edited 14d ago

It's like a bad recurring dream (page 219).

"Consider a requirement to maintain data about class schedules. We are required to keep the course, section, department, time, room, professor, student, major, and grade. Suppose that we initially set up a Pascal file with records that look like this: "

Why did we "initially set up a Pascal file with records that look like this"? It's 1999, we already have Delphi and MySQL.

"First normal form means that the table has no repeating groups. That is, every column is a scalar (or atomic) value, not an array or a list or anything with its own structure."

This completely ignores a) tuples such as lat/long b) simple-structured things such as addresses in well-run countries; c) simple algebraic data types such as Maybe monad, that also solves the "problem" of NULL.

Also, it's not clear how MVAs interact with the idea of "no list of anything".

I can go on and on, basically on every page.

And that's not a problem with Celko, basically every other RM textbook does the same with little rewriting. How can you learn anything from that.

Update: this is just insane (though typical):

"This schema is in 3NF, but it has problems. You cannot insert a new gift into our offerings and points unless we have a salary to go with it. If you remove any sales points, you lose information about the gifts and salaries (e.g., only people in the $30,000 range can win a car). "

why did you present this schema in the first place, dummy?

1

u/Creepy_Purchase_501 17d ago

I just gotta say, this is great info.

After working with data for nearly a decade, I recently started working on a pretty convoluted personal project, and while doing so I realized I was complicating the hell out of it and started questioning many of the conventional wisdoms. I tried looking for good resources(books), but found it oddly difficult - many were either too beginner surface level or too technology-specific. From a brief google search of the authors you mentioned, they are exactly what I was looking for. Genuinely, thank you for that.

Any specific works you’d recommend?

1

u/squadette23 17d ago

so I realized I was complicating the hell out of it and started questioning many of the conventional wisdoms.

I invite you to read another tutorial that I wrote: https://kb.databasedesignbook.com/posts/google-calendar/ Read the first sections: Introduction, Intended audience, Approach of the book, and Problem description.

1

u/Ultra-Ferric 16d ago

Instead of starting from the end product, why don’t we go back to the basics.
Take the first part, where you define the entities you want to model, each of their attributes, and break them down to the most granular level you need in plain English.
This is called a data dictionary

I think you have alread done some of it, but it has to be complete and without ambiguity.
Once you do that, I’ll guide you through building a simple data model, which eventually will become a SQL database.

I opened a new sub r/RelationalDataModel so I think it would be best to post it there.
I’ll monitor it daily and reply.

1

u/squadette23 16d ago

I think you have alread done some of it, but it has to be complete and without ambiguity.

See "Part 6. Complete logical model so far" https://kb.databasedesignbook.com/posts/google-calendar/#part-6-complete-logical-model-so-far

I believe that it is complete and without ambiguity. I have a problem with the word "complete" because of course we would continue developing our system, adding functionality. Your approach to database schema design needs to handle this because this is how the systems get developed.

So, it is complete up to the state of the MVP that we discuss. It is definitely "without ambiguity", but maybe I also have a fundamentally incorrect understand of ambiguity?

1

u/Ultra-Ferric 17d ago

I would start with Joe Celko's "Data and Databases: Concepts in Practice" and probably continue with "SQL for smarties". Joe's books are easy to digest, and his humor makes reading fun, while teaching complex subjects.

Chris Date is a more challenging read. It is academic theory oriented, but it is necessary if you really want to master the relational model.
I would start with his "E. F. Codd and Relational Theory" and "Relational Theory for Computer Professionals" and from there continue to either " Logic and Relational Theory", or "Domains and Types in Relational Theory and SQL". I haven't yet read his latest book about NULL, but I plan to do it soon.

Fabian's articles are probably the most hard-core of the bunch, but he does challenge the norms and provokes radical thought. Keep those for your third year of learning :-)

1

u/Lucky_Cable_3145 17d ago

I understand the concept but disagree it is always the correct design.

Why risk that level of complexity (to get global uniqueness) if it is unnecessary in your data model?

A bus company cares about the VIN of the bus (global ID), but in a given moment in time the bus company is more concerned with the route the bus is currently assigned (local ID).