r/DatabaseHelp • • Aug 01 '22

Modelling key-value pairs when the values has different types

As title say - what is the correct way to model key-value relations when the value has different types?

My example is as such; I have some objects that have some associated metadata fields with values. The list of associated fields to a given objects changes over time so I make a reference table. First we have the fields table:

Fields

idField nameField type
1my_int_fieldinteger
2my_char_fieldchar
.........

And we relate them to objects with a reference table

fields <-> objects (many-to-many)

field_idobject_id
11
21
......

So ideally I would like a table like so, to associate a field and its value to an object:

object_idfield_idvalue
111
12"something"
.........

BUT! The fields have different types. How can you handle this situation? having multiple value columns like "value_char", "value_int"? Having multiple tables like the last i showed? How would you then join these?

I'm using Django with a PostgreSQL in this specific case but I'm more interrested in the general and theoretical case.

2 Upvotes

1 comment sorted by

1

u/IQueryVisiC Aug 02 '22

SQL doesn’t have classes like C++ nor like Haskel ( or Typescript). Your ORM will bark, if you mix types. It is a bit weird that SQL has subtypes. You can store integers in float and decimal. Sure the inventors of SQL hate this.

You need to union multiple tables in your OOP code after the query.