# PostgreSQL json vs jsonb: Which to Use, and What Converting a Live Column Costs

> Use `jsonb` unless you need the exact text you were sent: `json` keeps whitespace, key order and duplicate keys, but the column itself cannot be indexed, compared, grouped or deduplicated, and every read parses it again. Converting a live `json` column to `jsonb` rewrites the table under a lock that blocks reads, fails outright on a `\u0000` escape or a lone surrogate, and silently keeps only the last of a duplicated key, so find those rows before the migration runs.

Source: https://schemity.com/blog/postgres-json-vs-jsonb/

Use `jsonb` for a JSON column in PostgreSQL unless your application needs back the exact text it stored. `json` keeps the input as text, with its whitespace, key order and duplicate keys, and pays for that on every read and every query that compares values. The decision is easy for a new column. It is harder for an old `json` column on a live table, because converting it rewrites every row, can fail on data you have never looked at, and changes some values without saying so.

Everything below ran on PostgreSQL 18.3 in a throwaway container, in a UTF-8 database. The test table holds 1M order events of about 150 characters each, inserted from the same compact text into a `json` table and a `jsonb` table:

```sql
CREATE TABLE events_json (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    payload json NOT NULL
);
CREATE TABLE events_jsonb (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    payload jsonb NOT NULL
);
-- each payload looks like:
-- {"meta":{"ip":"10.0.7.7","source":"web"},"type":"order.refunded","items":[{"qty":2,"sku":"SKU-7"}],"amount":9.59,"currency":"EUR","customer_id":7}
```

## Postgres json vs jsonb: which should you use?

Use `jsonb`: it was 6x faster to read a field from, it is the only one of the two whose column can be indexed or compared, and it costs some extra space and insert time.

The PostgreSQL manual's [JSON types page](https://www.postgresql.org/docs/18/datatype-json.html) gives the reason in one sentence: `json` "stores an exact copy of the input text, which processing functions must reparse on each execution", while `jsonb` is "stored in a decomposed binary format that makes it slightly slower to input due to added conversion overhead, but significantly faster to process". Its recommendation is just as direct: "most applications should prefer to store JSON data as `jsonb`, unless there are quite specialized needs, such as legacy assumptions about ordering of object keys."

On the 1M-row tables, with no index other than the primary key unless the row says so, each query repeated until the timing settled:

| | `json` | `jsonb` |
|---|---|---|
| Table size | 192 MB | 261 MB |
| Average value size | 159 bytes | 229 bytes |
| Insert 1M rows | 3.8 s | 6.0 s |
| `WHERE payload->>'type' = 'order.refunded'` | 425 ms | 72 ms |
| `WHERE (payload->>'customer_id')::int = 4242` | 424 ms | 131 ms |
| `WHERE payload @> '{"customer_id": 4242}'` with a GIN index | Not possible | 0.4 ms |
| `UNIQUE`, btree or GIN index on the column | Refused | Allowed |
| Keeps whitespace, key order and duplicate keys | Yes | No |

`jsonb` was 36% larger here. It drops the quotes and commas, but it stores an offset entry for every key and value and keeps numbers as `numeric`, which costs more on documents made of many short fields like these. The GIN index (`jsonb_path_ops`) added 35 MB. What you get for that is reading a field without parsing the whole document, and one index that serves containment queries on any key.

An expression index works on either type: `CREATE INDEX ON events_json ((payload->>'type'))` is accepted, and it makes that one filter fast on `json` too. The difference is that you need one per field you filter on, while a GIN index on a `jsonb` column covers containment on all of them.

## What can you not do with a json column?

You cannot compare `json` values at all, so anything that needs equality fails: `DISTINCT`, `GROUP BY`, `UNION`, `=`, a `UNIQUE` constraint, and every btree or GIN index on the column.

```sql
SELECT DISTINCT payload FROM e;
-- ERROR:  could not identify an equality operator for type json
SELECT payload, count(*) FROM e GROUP BY payload;
-- ERROR:  could not identify an equality operator for type json
SELECT * FROM e WHERE payload = '{"a":1}';
-- ERROR:  operator does not exist: json = unknown
ALTER TABLE e ADD CONSTRAINT e_payload_key UNIQUE (payload);
-- ERROR:  data type json has no default operator class for access method "btree"
CREATE INDEX ON e USING gin (payload);
-- ERROR:  data type json has no default operator class for access method "gin"
SELECT * FROM e WHERE payload @> '{"a":1}';
-- ERROR:  operator does not exist: json @> unknown
```

The `UNION` failure is the one that tends to show up late, in a reporting query written months after the column. Field access with `->` and `->>` works on both types, which is why a `json` column can go years without anyone noticing it is the wrong one: every read works, just slower than it should, and the first `GROUP BY payload` or containment query fails.

## When is json the right choice?

Choose `json` when the column is a record of exactly what you received, written once and read back whole, and nothing queries inside it.

`json` keeps the input as typed. `jsonb` normalizes it, so the same input reads back differently:

```sql
SELECT '{"b": 1,  "a": 2, "a": 3}'::json  AS as_json,
       '{"b": 1,  "a": 2, "a": 3}'::jsonb AS as_jsonb;
--           as_json          |     as_jsonb
-- ---------------------------+------------------
--  {"b": 1,  "a": 2, "a": 3} | {"a": 3, "b": 1}
```

That makes `json` a fair type for a raw webhook body or an audit log entry, where the point is to keep the text as it arrived. If a body has to be kept even when it is not valid JSON, or byte for byte, for example to check a signature computed over it, `text` or `bytea` is the safer column, because `json` refuses malformed input. `json` was also 26% smaller and inserted 1.6x faster in the test above, which matters for an append-only log nobody reads. As soon as a query filters, groups or joins on the contents, the column wants to be `jsonb`. A common split is both: the raw text for the record, and a `jsonb` column, or the fields you query as plain columns, for everything else.

## What does converting a json column to jsonb cost?

A full table rewrite under a lock that blocks reads, and it can fail partway through that rewrite or change values without an error.

The conversion is one statement:

```sql
ALTER TABLE webhooks ALTER COLUMN payload TYPE jsonb USING payload::jsonb;
```

On a `webhooks` table with 1M rows, three things happened in order.

First, a view that read the column stopped it before it started:

```
ERROR:  cannot alter type of a column used by a view or rule
DETAIL:  rule _RETURN on view paid_webhooks depends on column "payload"
```

The view has to be dropped and recreated around the change, as with [any type change under a view](https://schemity.com/blog/postgres-alter-column-type-used-by-view/).

Second, with the view gone, one row out of a million failed the whole statement after 3.2 seconds of rewriting:

```
ERROR:  unsupported Unicode escape sequence
DETAIL:  \u0000 cannot be converted to text.
```

`json` accepts a `\u0000` escape, because it only checks the syntax. `jsonb` rejects it, "because that cannot be represented in PostgreSQL's `text` type", in the manual's words. It also rejects a lone UTF-16 surrogate such as `"\ud800"`, which `json` stores without complaint and which JavaScript's `JSON.stringify` writes for half of a broken emoji. That one fails as `invalid input syntax for type json`, with `Unicode low surrogate must follow a high surrogate`. Nothing was converted, and the 3.2 seconds were spent holding the lock.

Third, after that row was deleted, the conversion took 3.6 seconds, wrote the table to a new file (`pg_relation_filenode` changed), and kept only the last value of a duplicated key without a warning: `{"amount":10,"amount":12}` became `{"amount": 12}`. Every row not already in `jsonb`'s own key order and spacing changed too, which here was all of them, and matters if anything compares the stored text or returns it to a client as-is.

During those seconds the statement holds an `ACCESS EXCLUSIVE` lock. With the conversion open in one session, a plain `SELECT` on the table in another waited and hit its `lock_timeout`. On a busy table, every query queued behind it waits too.

## How do you find the rows before converting?

Run one query for the values `jsonb` refuses, which fail the statement, and one for the duplicate keys it will silently collapse.

```sql
-- values jsonb refuses (PostgreSQL 16 and later)
SELECT id FROM webhooks
WHERE NOT pg_input_is_valid(payload::text, 'jsonb');

-- the same on any version: escaped backslashes out of the way first,
-- then valid surrogate pairs, then any \u0000 or surrogate left over
SELECT id FROM webhooks
WHERE regexp_replace(regexp_replace(payload::text, '\\\\', '_', 'g'),
        '\\u[dD][89abAB][0-9a-fA-F]{2}\\u[dD][c-fC-F][0-9a-fA-F]{2}', '_', 'g')
      ~ '\\u(0000|[dD][89a-fA-F][0-9a-fA-F]{2})';

-- objects whose top-level keys repeat
WITH valid AS MATERIALIZED (
    SELECT id, payload FROM webhooks
    WHERE pg_input_is_valid(payload::text, 'jsonb') AND json_typeof(payload) = 'object'
)
SELECT id FROM valid
WHERE (SELECT count(*) FROM json_object_keys(payload))
   <> (SELECT count(*) FROM jsonb_object_keys(payload::jsonb));
```

The version-independent query gave the same answer as `pg_input_is_valid` on 200,007 generated values, valid and invalid escapes mixed. The duplicate-key query filters first, in a materialized CTE, because `json_object_keys` fails on a refused value and on an array or a scalar, and a plain `AND` does not guarantee the order the conditions run in. It only sees top-level keys: a repeat inside a nested object such as `{"a":{"x":1,"x":2}}` is not found. All three scan the whole table, so run them on a replica or outside peak hours.

On a large table in production, most teams avoid the long lock by not converting in place, and every step of this ran on the same 1M-row table. Add a nullable `jsonb` column (10 ms) and a trigger that fills it on every insert and update before the backfill starts, so no row written during it is missed. Backfill in batches (100,000 rows took about 1 second) and fix or remove the refused rows as their batches fail. Add `CHECK (payload_jsonb IS NOT NULL) NOT VALID` and validate it, which scans without blocking writes. Then swap in one short transaction:

```sql
BEGIN;
SET LOCAL lock_timeout = '2s';
ALTER TABLE webhooks ALTER COLUMN payload_jsonb SET NOT NULL;  -- uses the validated check, no scan
ALTER TABLE webhooks DROP CONSTRAINT webhooks_payload_jsonb_not_null;
DROP TRIGGER webhooks_payload_jsonb ON webhooks;
ALTER TABLE webhooks ALTER COLUMN payload DROP NOT NULL;
ALTER TABLE webhooks RENAME COLUMN payload TO payload_json;
ALTER TABLE webhooks RENAME COLUMN payload_jsonb TO payload;
DROP VIEW paid_webhooks;
CREATE VIEW paid_webhooks AS
    SELECT id, payload->>'amount' AS amount FROM webhooks WHERE payload->>'type' = 'order.paid';
COMMIT;
```

The whole transaction took about 20 ms. The view has to be recreated inside it, because a view holds its columns by number, not name: without that step it keeps reading `payload_json`. The old column loses `NOT NULL` so new inserts, which no longer fill it, still work, and it stays until a later release drops it. Indexes and constraints on the old column do not move either and are rebuilt on the new one. The `lock_timeout` makes a swap that cannot get its lock give up and be retried instead of queueing every query behind it, and the backfill leaves about a table's worth of dead rows for `VACUUM`. It does not avoid the duplicate-key collapse: that still happens, one batch at a time.

## How does Schemity show this before the migration runs?

Schemity's lint flags a key PostgreSQL will refuse, and its impact analysis reports the rewrite, the lock and the blocking view, and in the next release counts the rows `jsonb` will refuse.

Schemity is database design software that reads your live database, shows the impact of every schema change before it runs, and keeps the diagram as a file in Git. When you design a table, [schema lint](https://schemity.com/doc/schema-lint/) (Schemity Pro) reports a `UNIQUE`, primary key or index on a `json` column as "Unique key on a column type the database cannot index, so creating it fails", with the reason "PostgreSQL has no btree operator class for JSON", and a GIN index on one with "PostgreSQL has no GIN operator class for json; jsonb has one." A GIN index on a `jsonb` column passes. In the test, PostgreSQL refused the same two statements lint flagged: the `UNIQUE` on the `json` column and its GIN index.

![Schemity's lint drawer on PostgreSQL 18.3 showing two Fails at runtime findings for a draft table audit_events with payload JSON (unique) and body JSONB: audit_events_payload_key, Unique key on a column type the database cannot index, so creating it fails, PostgreSQL has no btree operator class for JSON; and audit_events_payload_idx, Index on a column type the database cannot index, so creating it fails, PostgreSQL has no GIN operator class for json; jsonb has one. The GIN index on body is not flagged.](https://schemity.com/images/blog/postgres-json-vs-jsonb/lint-json-unique-gin.webp)

The change preview for the same draft shows the two statements PostgreSQL refuses, line 3's `UNIQUE` on the `json` column and line 6's GIN index on it, while line 7's GIN index on the `jsonb` column is accepted:

![Schemity's change preview for creating audit_events on PostgreSQL 18.3: the planned migration CREATE TABLE "audit_events" with "id" BIGINT GENERATED ALWAYS AS IDENTITY NOT NULL PRIMARY KEY, "payload" JSON NOT NULL UNIQUE and "body" JSONB NOT NULL, then CREATE INDEX "audit_events_payload_idx" ON "audit_events" USING gin ("payload") and CREATE INDEX "audit_events_body_idx" ON "audit_events" USING gin ("body"), one planned change, Table audit_events created, and Lint: 2 naming the unique key and the index on audit_events.payload.](https://schemity.com/images/blog/postgres-json-vs-jsonb/preview-create-audit-events.webp)

For the conversion, [impact analysis](https://schemity.com/doc/impact-analysis/) (Schemity Pro) reads the same change, made on the diagram or written as that `ALTER TABLE` in a migration file, and reports that it rewrites `webhooks` (~1M rows, 194 MB), blocks reads and writes while it runs, and is refused by the view `paid_webhooks`. In the next release it also says the change fails if a value does not fit, with an exact count of the values holding a `\u0000` escape or a lone surrogate, and it warns that values may not survive the cast, for the duplicate keys, key order and whitespace `jsonb` does not keep. That is the point of being able to see the impact of every change: the row that would have failed the rewrite is counted before the lock is taken.

![Schemity's change preview for webhooks.payload changed from JSON to JSONB on PostgreSQL 18.3: the planned migration ALTER TABLE "webhooks" ALTER COLUMN "payload" TYPE JSONB USING "payload"::JSONB, one planned change, Column webhooks.payload altered, lint with no findings, and five impact findings: values may not survive the cast (~1M rows), fails if a value does not fit (~1M rows), rewrites webhooks to change payload (~1M rows, 194 MB on disk), holds back reads and writes to webhooks while it reads ~1M rows, and 1 object depends on webhooks.payload and the database refuses the change, the view paid_webhooks.](https://schemity.com/images/blog/postgres-json-vs-jsonb/impact-json-to-jsonb.webp)

The preview shows the estimate. The exact count is in the impact drawer: on a copy of the table with a `\u0000` row, a lone surrogate and an escaped backslash followed by `u0000` added, Count exactly on the fails-if-a-value-does-not-fit line returned 2, the first two.

What it does not see is your application. Impact analysis reads the database, not your code, so it cannot tell you that an API returns the stored text and its clients will see the keys in a new order, or that a test compares the payload as a string. It does not look for duplicate keys at all: its warning covers every value, and the query above is how to find the rows. In a database whose encoding is not UTF-8, `jsonb` also refuses escapes for characters that encoding lacks, which the count does not include. Search the codebase for code that reads the column as text before converting it, and let the test suite cover the rest.

The same kind of choice for strings, where the default is the less restrictive type and a limit is a rule you opt into, is in [varchar vs text](https://schemity.com/blog/postgres-varchar-vs-text/).

## Frequently asked questions

### Should I use json or jsonb in PostgreSQL?

Use `jsonb` for almost every column: the column can take a GIN index, be compared with `=`, grouped and deduplicated, and reading a field from it was about 6x faster than from `json` in a 1M-row test on PostgreSQL 18.3. Use `json` only when you need the exact text you received, with its key order, whitespace and duplicate keys, and rarely query inside it.

### Why does `SELECT DISTINCT` fail on a json column?

The `json` type has no equality operator, so PostgreSQL cannot compare two values: `SELECT DISTINCT`, `GROUP BY`, `UNION` and `=` all fail with could not identify an equality operator for type json, or operator does not exist. A `UNIQUE` constraint or a plain index on the column fails too, because there is no btree operator class. Casting the column to `jsonb` fixes all of them.

### Does converting json to jsonb lock the table?

Yes. `ALTER COLUMN ... TYPE jsonb` rewrites every row and holds an `ACCESS EXCLUSIVE` lock until it finishes, so even plain `SELECT` statements on the table wait. On 1M rows it took 3.6 seconds in a test on PostgreSQL 18.3. To avoid the long lock, add a new `jsonb` column, keep it filled with a trigger, backfill it in batches and swap the names in one short transaction.
