Sobes.tech
Middle+

How does JSON differ from JSONB in PostgreSQL?

sobes.tech AI

Answer from AI

In PostgreSQL, the data types json and jsonb are used for storing JSON data but have important differences:

  • json — stores data as a text string, exactly as it was passed. Data is parsed anew with each query.
  • jsonb — stores data in a binary format, optimized for fast access and indexing.

Main differences:

  1. Performance

    • jsonb is faster for searching and filtering because data is already indexed and structured.
    • json is slower because it requires parsing the text on each query.
  2. Storage

    • jsonb takes up slightly more space due to the binary format, but this is offset by its speed.
  3. Index support

    • jsonb supports GIN and GiST indexes, enabling efficient queries by keys and values.
    • json does not support such indexes.
  4. Behavior on saving

    • jsonb normalizes data: removes spaces, sorts keys, which may change the original order.
    • json stores data as-is.

Example of using jsonb:

CREATE TABLE example (
    data jsonb
);

INSERT INTO example VALUES ('{"name": "Alice", "age": 30}');

-- Search by key
SELECT * FROM example WHERE data->>'name' = 'Alice';

In most cases, it is recommended to use jsonb due to better performance and functionality.

How does JSON differ from JSONB in PostgreSQL? — Golang - sobes.tech