I need to design a Key/value table in my database and I\'m looking for guidance on the best way to do this. Basically, I need to be able to associate values to a dynamic se
You are employing a database model called Entity-Attribute-Value. This is a common way to store key/value pairs in a relational database, but it has a number of weaknesses with respect to database normalization and efficiency.
Yes, the table design you showed is the most common way to do it. In this design, every attribute of every entity gets a distinct row in your KeyValue table.
Apply a key/value pair to a group of items: You need to add one row for each item in the group.
INSERT INTO KeyValue (id, key, value) VALUES (101, 'color', 'green');
INSERT INTO KeyValue (id, key, value) VALUES (102, 'color', 'green');
INSERT INTO KeyValue (id, key, value) VALUES (103, 'color', 'green');
You may also prepare the INSERT statement with parameters and run through a number of item id's in a loop, or whatever.
Enumerate all of the currently-active keys:
SELECT DISTINCT Key FROM KeyValue;
Determine all of the items that have a value for a given key:
SELECT id FROM KeyValue WHERE Key = 'color';
Determine all of the items where the value associated with a given key matches some criteria:
SELECT id FROM KeyValue WHERE Value = 'green';
Some of the problems with Entity-Attribute-Value are:
Basically, Entity-Attribute-Value is not a normalized database design.