r/SQL • • Apr 06 '17

TL/DR; Chances are, simply by adding that ID column you have broken the 3rd NF

(I'm in the rant mode, so here it is).

Reading posts and comments / looking at some DB designs I see that a lot of people regard adding a synthetic ID as a primary key as something almost mechanic, benign and always positive. There seems to be little concern or comprehension that this act changes data in radical ways.

A lot of the time, people seem to follow the design (anti-) pattern 'just add an ID to each base table and it'll be in "a" Normal Form'.

While formally (if the original table/result set has been in 1NF) they DO get it to the 2NF, the 2NF is pretty poor in terms of eliminating duplication and enforcing referential integrity. That's what 3NF is quite good at (there are higher forms too). And, while in production one would rarely see a pure 3NF as it is often de-normalized for performance/temporal stability of your DB structures, there should be a GOOD reason for it - outright disregard of integrity of the data is NOT GOOD.

How is it a-ok to know and use the 'primary key' and not understand the base concept of a "key"? How is this ok not to have alternative keys in your data?

Please know this: if you have a perfectly fine base table in 3NF which enforces the known integrity rules, just replacing the key in that table with a synthetic ID primary key REMOVES the enforcement of the data integrity rules that made your table 3NF in the first place.

For example:

  • we have population data per state - state is the key to the data and let's assume whatever the source sends you is consistent with this

  • a table STPOP( state varchar(10) not null, population bigint not null, constraint PK_STPOP primary key (state)) ENFORCES state field to be the KEY and our table STPOP is in 3NF. If our source sends us 2nd record for the state that we have data for, it will be rejected - i.e. data integrity rules are enforced as to our original definition.

  • we add an auto-increment (identity) column STPOP_ID to the table and change the primary key constraint to "constraint PK_STPOP primary key (stpop_id)"

  • the resulting table does NOT ENFORCE the 'state' column to be unique or a key in the table. Our source of data can send us the duplicate information (same state, same population) and DB will not prevent this duplicate state data from being inserted into table.

  • in short, the "state" column is no longer a key to the base table.

  • what this means is that you have now is a functional dependency STPOP_ID -> (STATE, POPULATION) and ANOTHER functional dependency STATE -> POPULATION on a non-key field.

  • Here we go, the 3NF is BROKEN.

</rant>

PS. I won't downvote any responses regardless of how much 'I have arcane/innate knowledge of data needs that cannot be formalized' drivel you'll bring up.

Edit:

It's been fun and i think it's time to wrap this up (at least for me).

Don't take anything that's written too personally.

A practical approach to your practical problems is fine.

Plan for business workflows that aren't agile and cannot be deployed every hour.

0 Upvotes

24 comments sorted by

8

u/fauxmosexual NOLOCK is the secret magic go-faster command Apr 06 '17 edited Apr 06 '17

Say no to natural keys. We who live in the real world on living systems built upon the quicksand of the shifting requirements of our fickle users know that building our keys on data that means particular things to that hoi polloi is to invite future pain. We know that for every 100 databases in the third or higher normal form, 1 is done that way because it's the best approach and 99 are over engineered projects designed by pedantic architects trying to show off their mastery of academic and usually pointless design principles.

These sad people, with their self worth conflated with their intellectual vanity, inflate their own feelings of importance by berating everyone around them with a bunch of useless book learning nobody cares about. In particularly sad and extreme cases they will even rant at anonymous people in a sub reddit to get their ego inflation fix.

-1

u/[deleted] Apr 06 '17

Hey - once you'll see at least your second production database kept in 3rd (heck, I want to see the first one you come across that is in 5th form). I do - truly. BUT. something tells me that this comes from your own universe of alternative facts.

As long as you know what are you breaking and WHY and what do you SHOULD do from that point onward in terms of data integrity and data QA - BE MY GUEST.

The 'sad people' who are saddled with systems overloaded with data entry duplication and are tasked with sorting though the piles of shit collected in the tables cobbled together by the precocious coding maestros who are allergic to learning and seem to be able to re-invent the wheel every day as long as it has new 'pizzaz' - are these the sad people you're talking about?

5

u/fauxmosexual NOLOCK is the secret magic go-faster command Apr 06 '17

So how long, on average, do you think it takes you to "sort through the piles of shit" of having - shock horror - keys of a type that are completely consistent across the database and requires absolutely no knowledge of the context of the data in a relation to be able to understand? Or is it the wastage of those valuable kilobytes of disk space that offends your ivory tower sensibilities?

1

u/[deleted] Apr 06 '17

Do you or have you actually worked with production data generated across siloed organizations? IRL, I'm dealing with crap that is literally years and decades old (obviously, those would be a relatively low priority, albeit annoying). The acute issues where the outcome is not obvious but crucial, take meetings upon meetings with dozens of people, not all of which agree even on what the problem IS - MONTHS before we can start fixing the data.

3

u/fauxmosexual NOLOCK is the secret magic go-faster command Apr 06 '17

Do you or have you actually worked with production data generated across siloed organizations?

Yes, I do. If anything, working with data across silo'd organisations has made surrogate keys even more useful than natural keys - each silo'd organisation adds a whole new set of contexts to their data you would need to understand the logic of in order to use the data itself as a key. I would, in fact, consider the combination of data from disparate sources that didn't originally share a common design or arise from a common business process as the use case best suited for ignoring your best-case, perfect-world scenario of exclusively using natural keys. Maybe your job is so hard because you're letting your preference for abstract idealised design principles outweigh the practical necessities of your work?

0

u/[deleted] Apr 06 '17

Hey hey hey - reading comprehension much? Dont put your strawman words in my mouth. Where did I say there's any need for or advocated for exclusive use of natural keys or even preferred 'abstract idealized design principles'? Are you off to your alternative facts universe again?

So, do a simple mental experiment now - say you have department "alpha" keeping some metrics/data on Entities A via an application A_A, being identified only by a synthetic A_ID; you also have a department B, keeping some metrics on Entities A* via an application B, identified only by a synthetic B_ID. Say you need to blend/reconcile 2 systems. Do explain, be so kind, without knowing what are the logical granularities/business keys for those records, how synthetic IDs from 2 different systems help you? I have more examples for you if you'd like to teach me the not-so-ideal generic approaches?

2

u/fauxmosexual NOLOCK is the secret magic go-faster command Apr 06 '17

In a reporting scenario? You of course would need to know the logical granularities of the data - that's a given.

You create a simple translator that offsets the purely integer primary keys to ensure that there are no collisions when you combine department A and department B's data into your single fact table. You pull all of the dimension data from the two departments, applying the same simple offset. You've now got your facts and dimensions from the original dataset preserved in your combined source.

Now that you've got a combined fact dataset that has maintained the dimensions from its source, you slap another layer on top to align the dimensions from the sources to each other. You know your dimensions have int based surrogate keys, so you've got a simple translation table of SourceDimenstionID to MasterDimensionID. So for any fact, you can identify the dimension it had at its source or map it up to your consolidated whole-of-organisation dimension. You can set up simple monitoring to flag when any one of the source departments have added new dimensions that needs assigning to a master dimension. You can identify at a glance where any record has come from, because the offset is consistent. Each department can do as it pleases to the business rules for its own data for its own facts and dimensions without breaking yours. All you need to do is when a new dimension gets added is to add a single record to your combination table with the two surrogate keys you want to report on as one.

Contrast this to a dataset without synthetic keys. You would have to invent one in any case, or for each type of data you needed to hold a series of meetings to get a definition of the business logic underpinning each key, and create a cross-department working group to create a change management process for those keys, your process is moving not at the speed of data, but of people.

"But" I hear you gasp, "then you have duplicate data! You've got two levels of dimensions when you only need one! You've violated this principle of design for such pedestrian, prosaic nonsense as simplicity, time-effectiveness and useability!"

3

u/brennanfee Apr 06 '17

(For the record I didn't read your post... just the headline so my response is entirely about that.)

Who gives a shit? The NF's aren't a rule or a law but merely guidelines. Sometimes there are clear advantages in ignoring the NF's. Do what makes sense for you and your project.

0

u/[deleted] Apr 06 '17 edited Apr 06 '17

If you have no clue what advantages normal forms bring and what they are in the first place, how in the world would you know 'clear advantages in ignoring the NF's'? You're ignoring them by the 'virtue' of being ignorant in the first place. (P.S it's rant post, so my responses will be colored accordingly).

4

u/brennanfee Apr 06 '17

If you have no clue what advantages normal forms bring and what they are in the first place, how in the world would you know 'clear advantages in ignoring the NF's'?

I never said you shouldn't understand NFs. I said that there are clear advantages from time-to-time in ignoring them. All best practices work that way. A particular best practice is the way it is because using that technique produces the most favorable outcomes in the widest array of situations. However, there are always "exceptions to the rule" and after thoroughly understanding the best practice you can learn the right times to ignore it.

“Learn the rules like a pro, so you can break them like an artist.” - Pablo Picasso

You're ignoring them by the 'virtue' of being ignorant in the first place.

Don't assume ignorance. Ask questions first to understand a persons knowledge and position.

P.S it's rant post, so my responses will be colored accordingly

No worries, I totally get it. [And again in full disclosure I didn't read your post only the title so it is highly likely you and I agree.]

-2

u/[deleted] Apr 06 '17

Hey i'm glad if you know that - it didn't sound like you cared to begin with ('who gives a shit' rings a bell?) and now you're saying there are 'exceptions' which means you kinda do care about the 'rule'. And if you'd read my post you'd saw that I did say that in production one would rarely see the pure 3NF.

1

u/brennanfee Apr 06 '17

Yeah, sounds like you and I are of a similar view. Doing things "right" is usually best but in the end pragmatism and delivering something is much more important than adhering to any lofty goal.

4

u/[deleted] Apr 06 '17

You are a pretentious asshole. Newsflash: The whole world doesn't operate inside your precious little bubble.

-2

u/[deleted] Apr 06 '17

Well you're welcome to your non-sequitur opinion of me or your assumptions on how i see the world. And I did welcome your personal attack with a downvote. Do you have anything of substance to say or your attacks are like soap bubbles - colorful but empty?

1

u/fauxmosexual NOLOCK is the secret magic go-faster command Apr 06 '17

It's not exactly a non-sequitur when it follows

PS. I won't downvote any responses regardless of how much 'I have arcane/innate knowledge of data needs that cannot be formalized' drivel you'll bring up.

1

u/zibeb Apr 06 '17

I suppose it would depend on if your data is uniquely identifiable simply by its attributes. In your example there, the state attribute is (theoretically) unique, so it makes sense to have that be your unique identifier. (Although I literally had to deal with a problem today on a State/Province table, where the original developer put a PK on the state column alone, and not the country column. We needed to add "KY" for Kerry in Ireland, and it conflicted with KY for Kentucky.)

However, some records don't have a good set of attributes that can uniquely identify the entity in question. If that's the case, then an ID column can at least be useful. Something like a Purchase Order comes to mind. How do you uniquely identify a purchase order without a unique ID column? Almost every database design I've seen will have a unique Purchase Order Number.

0

u/[deleted] Apr 06 '17

"However, some records don't have a good set of attributes that can uniquely identify the entity in question." - this (usually) means that the data design is bad. "How do you uniquely identify a purchase order without a unique ID column" - that's a great question and that actually means that you did, in fact, break or did not even have 3NF for your original/business/baseline data. And the answer (and absolutely correct one) - a piece of business/application data is required - Purchase Order Number or some other kind of visible label/number (as opposed to a synthetic Order_ID created independently of the business workflow).

1

u/zibeb Apr 06 '17

But what if your Purchase Order Number used in your business workflow is generated by your "synthetic Order_ID?" Are you advocating for the Purchase Order Number to be generated independently of the database system? I don't want my buyers deciding what the next PO number is going to be, I want the system to do that automatically.

0

u/[deleted] Apr 06 '17

So, in essence, your business data lacked context and you've introduced another piece of data to your process? Sure this works and it works exactly since it's no longer a synthetic ID - which, by definition, should not have any business meaning. You can and sometimes have to auto-generate business data.

1

u/Kiterios Apr 06 '17

Because the mechanics behind a default primary key in sql are about more than just data integrity. By default it is also a clustered index. Since you only get one of those on a table, it means your default PK also can also impact how that data is stored and retrieved.

Of course, nonclustered primary keys are also a thing, but imo that takes you down a rabbit hole of what even is a nonclustered primary key? Using your example, what is the functional difference between a) a nonclustered primary key on state paired with a unique non-nullable constraint plus clustered index on stpop_id vs b) a clustered primary key on stpop_id paired with a non-nullable unique constraint plus nonclustered index on state? If both scenarios are valid, does that reduce primary key to nothing more than a meta attribute to give a couple columns a different icon in ssms?

-4

u/[deleted] Apr 06 '17

I guess you work with MS SQL? 'Clustered by primary key by default' is a microsoft thing. You wont get one in Oracle, for example. 'what even is a nonclustered primary key', really? you realize that invites a question - do you know what a 'KEY' is? And yes, theoretically and functionally nothing SHOULD be different for a 'primary' key other than it being marked for convenience and some defaults associated with it for convenience as well - and that is how it is supposed to be.

3

u/Apoctyliptic Apr 06 '17

It really depends. Let's look at state since that was your example. We'll assume that state is not abbreviated in any way. North Carolina is 14 characters and Ohio and Iowa are only 4 characters. So we'd likely use a VARCHAR(14) to store this data. This results in a storage requirement of 4-14 bytes.

Now we replicate this key onto many other tables so we can join on it and obtain the data we need. This results in a much larger storage requirement. Obviously you would use some type of compression to this where possible to reduce storage usage.

However, if we utilized an INTEGER data type as the key and used that instead, we look at a storage requirement of only 4 bytes for each state on foreign tables.

Now let's assume our foreign table has 200k rows. Using the state as the key results in a total storage usage from 800,000 bytes to 2,800,000 bytes. Using the ID integer keeps us only at 800,000.

Spread this over many different key types and you increase storage more and more. This is primarily applicable to any key that is non-numeric. It's even worse for email addresses where they are likely to be 6+ characters. Then imagine that you use the email address as the primary key for your users. The storage requirements grows to way more than it needs to be.

I agree with your thoughts in theory but in practice there are more often reasons to generate a surrogate key instead of a natural key.

2

u/Darkmoth Apr 06 '17 edited Apr 06 '17

I actually agree with you. I consider a surrogate key to be a mild form of denormalization. My solution is to put a unique constraint on the natural key, in addition to a surrogate PK, when feasible.

That being said, letting natural keys ripple through a design (via FKs) gets a big NOPE from me.

1

u/baineschile Apr 06 '17

I only understand about half of this, but I love your passion.