I took a long (over a year) break from database design and im just comming back.
I am designing a database for the website that i am creating. I am storing 2 boolean values in one table (two separate columns). I realized that if first value is true the other one will also always be true but if the first value is false the other one can be true or false. As far as im concerned this is not a transitive dependency and I shouldn’t create a new table but I want to make sure that I’m doing everything right. If there were multiple values that behave like the second boolean value would I still keep it in the same table?
What is the best way to store this kind of data in a database?
I would appreciate if the anwser included an ER Diagram.
Normalized:
I think we should distinguish two cases:
The first case can be solved using a single table with two fields, since it guarantees both good performance and space optimization (you can’t save more space than this way, except if you ignore Normalization Rules, which I did in the last of these solution):
Concerning the second case I came up with two ideas, none of which I’m satisfied with.
The main thing we can say is that when you have long sequences, a column for each boolean value isn’t very handy. Here are my two ideas:
a single table with a PK, a boolean field and a self-referencing foreign key:
thisBoolclearly contains a boolean value.If
thisBoolis true you’re done, you don’t need to store the following boolean value, since its value matches the first one.If
thisBoolis falseidNextBoolpoints to the following boolean.This solution allows forward-search only.
a single table with a PK, a boolean value and a self-referencing foreign key:
If
idNextBoolis null, you’ve reached the first value of the sequence. OtherwiseidNextBoolpoints to the following boolean.This solution allows backward-search only.
As you can see the solutions for the second case (sequences longer than 2 values) are rather un-manageable.
That’s why I propose a non-normalized solution.
Not Normalized:
You could treat these boolean values as bits of a numerical field (especially considering that a boolean is in fact represented by a bit). Let’s say we have two fields,
field1andfield2, and consider that we can put them in one single field (let’s call itmyfield):As you can see you can extend this to as many boolean values as you can fit inside a numerical field (for example in a 32bit numerical field you can store 32 boolean values, as long as each one depends on the lower ones).