Sobes.tech
Junior — Middle

Can you explain what JSONB data type in a database is and how it differs from regular JSON?

sobes.tech AI

Answer from AI

The JSONB data type in a database, such as PostgreSQL, represents binary storage of JSON data. Unlike regular JSON, which stores data as text, JSONB stores it in a binary format, which allows:

  • Faster search and filtering operations based on content.
  • Use of indexes to speed up queries.
  • Elimination of key duplication and object ordering.

Example of usage in PostgreSQL:

CREATE TABLE example (
    data JSONB
);

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

-- Search by key using an index
CREATE INDEX idx_data_name ON example USING gin ((data -> 'name'));

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

Thus, JSONB is more efficient for working with JSON data when performance and complex query capabilities are important.