Suppose I have a Table1, with three Columns: ID (Primary Key, Identity), A, and B
Now, suppose I have 3 methods, assuming they share nothing in common column-wise:
Method 1: C, D, E
Method 2: F, G, H, I
Method 3: J
I could make one table:
ID, A, B, C, D, E, F, G, H, I, J, M
Where M, is the name of the Method (or a Method ID).
However, if 90% of the time Method 3 is used, there would be many null values.
Is this a problem? If so, is there a better way to set this up?
If I make each method its own table entity, how do I ensure each ID has exactly one method matching for it?
If I keep it as one table, how do I ensure ONLY C, D, E are filled in and F thru J are NULL if M is 1?
OK, seems some people had difficultly thinking abstractly, so I’ll create a random concrete example applying the above:
Suppose I had records of people performing exercises.
Each record would always have an ID (to uniquely identify the event), a TIME_STARTED, and TIME_ENDED.
However, depending on which exercise they did, there would be different attributes needed. Suppose there were only three exercises:
Elliptical: INCLINE, LEVEL, SPEED
Crunches: User_Weight, Reps, Delay, Extra_Weight
Dead Lift: Weight_Lifted
For each ID there could be only one “method”. Applying this, see above questions.
It sounds like you have a supertype/subtype situation here. In this case, Table1 holds your supertype, and you would want to create a different table to hold each of your subtypes. The PK on these subtype tables would also be an FK to the supertype table. So you would have something like this:
The point of this schema is to make sure that you don’t have a bunch of rows which are mostly nulls. For each method, you would have to write a separate query that would insert/update the appropriate table. With SQL Server, you can make a view which combines all these tables and abstracts away any joins:
So then you could just write something like:
EDIT : For OP’s comment
In order to ensure that each ID is in one and only one table, you need some kind of identifier on the supertype table. So if you had a column called TypeID, you would create the function:
Then, using that, you can create a check on each of the subtype tables: