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:
-
Performance
jsonbis faster for searching and filtering because data is already indexed and structured.jsonis slower because it requires parsing the text on each query.
-
Storage
jsonbtakes up slightly more space due to the binary format, but this is offset by its speed.
-
Index support
jsonbsupports GIN and GiST indexes, enabling efficient queries by keys and values.jsondoes not support such indexes.
-
Behavior on saving
jsonbnormalizes data: removes spaces, sorts keys, which may change the original order.jsonstores 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.