Sub topic 1
json versus jsonb: how each type stores data
PostgreSQL has two data types for JSON: json and jsonb. Both accept the same JSON text and both reject invalid JSON. They differ in what they keep after the text arrives, and that difference affects speed, indexing, and what your queries return. This chapter explains how each type stores data and gives you a rule for choosing between them.
Prerequisites
This chapter assumes you already have the following:
- Basic SQL:
SELECT,INSERT,UPDATE,WHERE, andJOIN. - Familiarity with JSON syntax: objects, arrays, strings, numbers, booleans, and
null. - Basic PostgreSQL data types and
CREATE TABLE. - Access to a PostgreSQL instance, version 12 or later. Every example here also runs on newer versions.
Run the examples in psql or any SQL client. Use a scratch database, because the chapter creates a demo table.
Two types, one input format
Both types take JSON text as input. A cast from a string literal is the quickest way to see the difference.
SELECT '{"b": 1, "a": [1, 2], "a": 3}'::json AS as_json,
'{"b": 1, "a": [1, 2], "a": 3}'::jsonb AS as_jsonb;The result looks like this:
| as_json | as_jsonb |
|---|---|
| `{"b": 1, "a": [1, 2], "a": 3}` | `{"a": 3, "b": 1}` |
The json column returned the input exactly as written, including the extra spaces, the key order, and both "a" keys. The jsonb column returned a cleaned-up document with one "a", the keys reordered, and normalized spacing.
How json stores data
The json type stores an exact copy of the input text. PostgreSQL checks that the text is valid JSON when you insert it, then keeps the text as it is. Because of this, json:
- Preserves whitespace.
- Preserves the order of keys.
- Preserves duplicate keys. Functions and operators that look up a key treat the last duplicate as the operative value, but the stored text still holds all of them.
- Preserves number formatting, such as
1.230e-5.
The cost shows up at query time. A json value is plain text, so every operator or function that reads inside it must parse the text again. If you extract three keys from one row, PostgreSQL parses that document three times. Insertion is fast because it only validates the text.
How jsonb stores data
The jsonb type converts the input into a decomposed binary format when you insert it. The "b" stands for binary. The conversion takes a little more time on insert, but later reads are faster because PostgreSQL does not reparse text. Key lookups use the binary structure directly.
Converting to a binary structure changes what is preserved:
- Whitespace is discarded.
- Keys are not kept in input order. PostgreSQL sorts them internally, shorter keys first and then by bytes.
- Duplicate keys are collapsed, and the last value wins.
- Numbers are stored as PostgreSQL
numeric, so their formatting can change.
You can see the number change here:
SELECT '{"reading": 1.230e-5}'::json AS as_json,
'{"reading": 1.230e-5}'::jsonb AS as_jsonb;The json result keeps 1.230e-5. The jsonb result shows 0.00001230. The value is the same number. Only the text form differs, and the trailing zero is kept because numeric remembers its scale.
The sorted key order is visible too:
SELECT '{"bb": 1, "a": 2, "ccc": 3}'::jsonb;
-- {"a": 2, "bb": 1, "ccc": 3}The next diagram shows how the same input is handled by each type.
Comparing the two in a table
The following table sets out the differences you are most likely to meet.
| Property | json | jsonb |
|---|---|---|
| Stored as | Exact text | Decomposed binary |
| Input speed | Faster | Slower, because of conversion |
| Query speed | Slower, because it reparses text | Faster |
| Whitespace | Preserved | Removed |
| Key order | Preserved | Not preserved |
| Duplicate keys | All kept | Last one kept |
| Equality operator `=` | Not available | Available |
| GIN indexing | Not supported | Supported |
| Containment and existence operators (`@>`, `?`) | Not available | Available |
Equality and comparison
Because jsonb normalizes documents, two documents that differ only in key order or spacing are equal:
SELECT '{"a": 1, "b": 2}'::jsonb = '{"b": 2, "a": 1}'::jsonb AS same;
-- trueThe json type has no equality operator, since comparing exact text would not mean "same data". This statement fails:
SELECT '{"a": 1}'::json = '{"a": 1}'::json;
-- ERROR: operator does not exist: json = jsonThis matters for DISTINCT, GROUP BY, and UNION on JSON columns. These operations need equality or ordering, so they work on jsonb and fail on json. The workaround for json is to cast to jsonb or to text, depending on what "equal" should mean for you.
Validation happens in both types
Both types reject text that is not valid JSON, so you do not need jsonb to get syntax checking.
SELECT '{"a": 1,}'::json;
-- ERROR: invalid input syntax for type jsonjsonb has one extra restriction. It rejects the Unicode escape \u0000 (the null character), because PostgreSQL text cannot hold a null character. The json type accepts that escape on input, but any later operation that must convert the value to text can fail.
SELECT '{"a": "\u0000"}'::jsonb;
-- ERROR: unsupported Unicode escape sequenceSeeing the difference in a table
Create a demo table with one column of each type and load the same document into both.
CREATE TABLE json_demo (
id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
as_json json,
as_jsonb jsonb
);
INSERT INTO json_demo (as_json, as_jsonb) VALUES
('{"name": "Ada", "tags": ["sql", "json"], "name": "Ada L."}',
'{"name": "Ada", "tags": ["sql", "json"], "name": "Ada L."}');
SELECT as_json, as_jsonb FROM json_demo;The json column returns the document with both name keys and the original spacing. The jsonb column returns {"name": "Ada L.", "tags": ["sql", "json"]}.
The access operators also return the matching type. The -> operator on a json column returns json, and on a jsonb column returns jsonb. The next chapters cover these operators in detail, but this query shows the effect:
SELECT json_typeof(as_json -> 'tags') AS json_side,
jsonb_typeof(as_jsonb -> 'tags') AS jsonb_side
FROM json_demo;Both columns report array. Note the function names: json_typeof takes json, and jsonb_typeof takes jsonb. Most JSON functions come in these paired forms, and calling the wrong one gives a "function does not exist" error or forces an implicit cast that you may not want.
Storage size
You can measure how many bytes a stored value takes with pg_column_size:
SELECT pg_column_size(as_json) AS json_bytes,
pg_column_size(as_jsonb) AS jsonb_bytes
FROM json_demo;Do not expect a fixed winner. A jsonb value carries structural headers, so small documents can be larger than their json text. Documents with lots of whitespace or duplicate keys can be smaller as jsonb. For both types, PostgreSQL compresses and moves large values out of the main table row automatically (a mechanism called TOAST), so very large documents behave similarly on disk.
Edge cases to watch for
- Numbers beyond a double. JSON in JavaScript clients usually uses 64-bit floating point.
jsonbstoresnumeric, so it holds large or precise values exactly. A client that parses the result as a float can silently lose digits. Exactness on the server does not guarantee exactness in the application. - Key order assumptions. If your application relies on key order, such as ordered form fields or a sequence you display,
jsonbwill break that. Store such data in an array, where order is part of the value. - Duplicate keys. Duplicate keys in input are usually a bug in the producer.
jsonbhides the problem by silently keeping the last value, whilejsonkeeps the evidence. - Exact text requirements. If you must reproduce the original bytes, for example for a signature check or an audit log of received requests,
jsonbcannot do it. Usejsonor plaintext. - Mixing types. Passing a
jsonvalue to ajsonbfunction needs a cast, such asas_json::jsonb. Castingjsontojsonbapplies the normalization described above, and the cast cannot be undone.
Choosing between them
Use jsonb by default. Most applications query their JSON, and jsonb gives you faster reads, equality, containment operators, and GIN indexes, which later chapters rely on. Choose json only when one of these holds:
- You need the exact original text, including whitespace, key order, or duplicate keys.
- The data is written once, read as a whole, and never queried inside the database, so the cheaper insert matters and the slower parsing does not.
Many teams skip json entirely and use text for the exact-copy case. That is a reasonable choice, because it also avoids implying that the database will interpret the contents.
The rest of this tutorial uses jsonb. The operators you learn next work on both types where noted, but the indexing, containment, and modification chapters apply to jsonb only.
Exercise
You run SELECT '{"x": 1, "y": 2, "x": 3}'::jsonb;. What does it return, and what would the same query return if you cast to json instead?
Show answer
With jsonb it returns {"x": 3, "y": 2}. The duplicate key x collapses to the last value, and the keys are in sorted order. With json it returns the input text unchanged, {"x": 1, "y": 2, "x": 3}, with both x keys.
Exercise
A table has a payload json column. The query SELECT DISTINCT payload FROM events; fails with "could not identify an equality operator for type json". Give two ways to fix it and say when each is appropriate.
Show answer
Cast the column to jsonb, SELECT DISTINCT payload::jsonb FROM events;, when documents with the same data but different key order or spacing should count as equal. Cast to text, SELECT DISTINCT payload::text FROM events;, when documents should count as equal only if their exact text matches. The longer-term fix is to change the column type to jsonb if you do not need the original text.
Exercise
Your service must store each incoming webhook body so that you can later verify its signature against the exact bytes received, and you also want to search by the event_type key. Which column types would you choose?
Show answer
Store the raw body in a text (or json) column so the exact text is preserved for signature verification, and add a jsonb column holding the same body cast to jsonb for searching and indexing on event_type. A single jsonb column would not work, because jsonb changes whitespace, key order, and duplicate keys, which would break the signature check.