What considerations are involved in choosing between a jsonb column and a composite type column of the same structure?
For example, consider a column like that used in the Postgres documentation:
CREATE TYPE inventory_item AS (
name text,
supplier_id integer,
price numeric
);
What are the tradeoffs involved between this approach vs a jsonb column mirroring this structure?
For example, I suspect that the composite type won't require storing the key names for every record, whereas the jsonb type would require this.
Best Answer
The TYPE inventory_item was defined in the question (same as in the guide), so we need only to define tables tc with composite (ROW) type, and tj with JSONb type.
INSERT TIME
Of course, we need loops, etc. something por complex to test... But seems "comparable" times, no big difference.
SELECT NATIVE TIME
Only retrieving the original datatype. Need good benchmark, but lets imagine something simple only to check big differences.
no difference again. Both with "Execution Time: ~460".
EXPLODE TIME
Seems that is very fast to transform JSONb-object into SQL-row! Seems a binary cast: we can suppose that the function
jsonb_populate_record
maps the JSONb types to SQL using byinventory_item
internal definition.And it is faster tham composite table.
Explode and calculate something
Perhaps ~150 ms to calculations, so same expected time... There are some error in the example above, need better benchmark to check real difference.
Check comparative time to cast from text.
Long and same times. Seems that
(x->'supplier_id')::int
it is only a sugar syntax for(x->>'supplier_id')::int
or(x->'supplier_id')::text::int
.PS: this answer is also a complement for this other question, about "Binary to binary cast with JSONb".