Stephen Bugs Kamenar Stephen Bugs Kamenar - 4 months ago 6
SQL Question

Postgres using a JSONB column instead of defined columns

Postgres has a lot of support for JSON (even indexing). I want to just put 1 jsonb field called

instead of defining of bunch of typed columns (mongodb style).

But I assume this is a bad idea. My question is: Why shouldn't I do this? Is the only con just the fact that it'll probably take extra storage space?

(My table has a lot of optional fields which is why I want to do this)


I can think of a few reasons:

  • If the JSON blob has foreign keys to other columns, I don't think you can add a REFERENCES constraint.

  • With columns you can enforce NOT NULL constraints very easily, but with JSON you'll have to write CHECK constraints for each required value.

  • JSON has fewer types than Postgres. For instance, no date/time/timestamp, no intervals, no ranges, just one kind of numeric type, no IP addresses, no binary data.

  • Over time if you add/move/delete fields in the JSON structure, you'll find that older rows become obsolete and have JSON your app doesn't understand. Using regular columns forces you to keep the whole table up-to-date.