Sobes.tech
Middle

How do JSON and JSONB differ in PostgreSQL?

sobes.tech AI

Answer from AI

In PostgreSQL, the data types JSON and JSONB are used for storing JSON structures but differ in internal representation and performance.

  • JSON stores data as text, in the form it was passed. Each query involves parsing the text into a data structure.
  • JSONB (Binary JSON) stores data in a binary format, which is already parsed and optimized for fast access and indexing.

Main differences:

  • JSONB supports indexes (GIN, GiST), which speeds up content search.
  • JSONB takes up slightly more space but is faster to process.
  • JSON preserves formatting and key order, JSONB does not.

Example of using JSONB with an index:

CREATE TABLE documents (
  id serial PRIMARY KEY,
  data jsonb
);

CREATE INDEX idx_data ON documents USING gin (data);

SELECT * FROM documents WHERE data @> '{"key": "value"}';

If query speed and searching JSON are important, it is better to use JSONB.