Sane way to store different data types within same column in postgres?

You’ve basically got two choices:

Option 1: A sparse table

Have one column for each data type, but only use the column that matches that data type you want to store. Of course this leads to most columns being null – a waste of space, but the purists like it because of the strong typing. It’s a bit clunky having to check each column for null to figure out which datatype applies. Also, too bad if you actually want to store a null – then you must chose a specific value that “means null” – more clunkiness.

Option 2: Two columns – one for content, one for type

Everything can be expressed as text, so have a text column for the value, and another column (int or text) for the type, so your app code can restore the correct value in the correct type object. Good things are you don’t have lots of nulls, but importantly you can easily extend the types to something beyond SQL data types to application classes by storing their value as json and their type as the class name.

I have used option 2 several times in my career and it was always very successful.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)