Database Design Using Key-Value Tables - Drawback no. 2: Awkward use of database constraints
(Page 4 of 5 )
Database constraints help us keep our data correct.
In the above (EMPLOYEES) example, assuming that our company was founded in 2004, let's figure that we want to keep our data integrity in such a way that the employee start working date will always be between 2004 and 2005.
All we have to do in scenario no. 1 is add a check constraint that will enforce this rule. Check constraints place a value restriction on the contents of a column, allowing the table owner to define which exact values are permitted for this specific column. Such a constraint creation would look like this:
ALTER TABLE EMPLOYEES ADD CONSTRAINT START_WORK_YEAR_CK CHECK (START_WORK_YEAR >= 2004 AND START_WORK_YEAR <= 2005);
By defining such a constraint, a DML attempting to update a value of the column START_WORK_YEAR with values above 2005 or below 2004 would fail, with an error indicating that the update failed due to our check constraint (START_WORK_YEAR_CK).
In scenario 2, there is also an option to add such a database constraint. Consider the following constraint added:
ALTER TABLE EMPLOYEE_ATTRIBUTES ADD CONSTRAINT START_WORK_YEAR_CK
CHECK ( 1 = CASE KEY1
WHEN 'START_WORK_YEAR' THEN
CASE VALUE1
WHEN '2004' THEN 1
WHEN '2005' THEN 1
ELSE 0
END
ELSE 1
END
);
As you can see, the above constraint use is possible but cumbersome, and most important, it will force us to add a constraint for each new ATTRIBUTE, which means that the model is no longer generic.
Next: Drawback no. 3: Problematic use of AND operator when relating to more than one attribute in the query criteria >>
More MySQL Articles
More By Tal Olier