Nov 23, 20265 min read

Postgres JSON vs JSONB

How json and jsonb differ in Postgres: storage format, duplicate keys and key order, operators and indexing, write and read cost, and the narrow cases where plain json is still the better column type.

Illustration for Postgres JSON vs JSONB

Postgres has two JSON column types, and the choice between them is one of the few database decisions with a clear default: jsonb for anything you query, json only when the exact text matters.

The differences come from how each one stores data, and that also explains the two cases where plain json still wins.

At a glance

jsonbjson
StorageDecomposed binary formatThe input text, unchanged
Duplicate keysLast value winsAll kept
Key order and whitespaceNot preservedPreserved
Containment @>, existence ?YesNo
GIN indexYesNo
Write costParse and convert on insertValidate only
Read costNo reparsingReparsed on every access

How each type stores data

The JSON types documentation describes json as an exact copy of the input text that processing functions must reparse on each execution, while jsonb is stored in a decomposed binary format that is slightly slower to input because of the conversion and significantly faster to process. The binary form also normalizes the document:

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}

On a small three-key product attribute document such as {"color":"red","size":"M","sku":"ABC"}, pg_column_size reported 42 bytes for json and 51 for jsonb on a local Postgres 17 test, so jsonb is not automatically smaller. The difference shrinks or reverses on larger documents, and it is rarely the deciding factor.

Querying and indexing

The operators that make JSON columns useful in a backend, containment @> and the key-existence operators ?, ?| and ?&, exist only for jsonb, as listed in the JSON functions and operators reference. Trying @> on a json column fails with "operator does not exist".

jsonb columns can carry a GIN index, either the default jsonb_ops for containment and key existence or jsonb_path_ops for containment only, which is smaller. Both are covered in the GIN index guide, and with one in place a filter such as attributes @> '{"color":"red"}' stays fast on millions of rows.

When json is the right choice

  • Signed payloads you may need to verify again. Webhook providers sign the raw request body, so key order and whitespace matter. Keep the exact bytes in a json or text column (or object storage), and parse the fields you need into jsonb or regular columns.
  • Write-heavy logs that are rarely read. If a column is written constantly and only read during an incident, skipping the conversion on every insert can be worth it.

Everything else, including settings, product attributes, feature flag rules and API responses you cache and filter, belongs in jsonb.

JSONB or regular columns?

jsonb is flexible, but fields that every row has and that you join on, sort by or enforce constraints on are better as typed columns. A common split is typed columns for id, status, customer_id and amounts, plus one jsonb column for the attributes that vary by product or tenant. Foreign keys and NOT NULL constraints do not work on keys inside a document, as the constraints documentation only defines them on columns.

Best fit: jsonb for flexible attributes you filter on, json or text for exact payloads you must reproduce byte for byte.

JSON columns in Encore

Encore

Encore is a backend framework with built-in infrastructure, and this TypeScript example keeps both column types in one catalog service: the raw supplier payload in json, and the attributes the storefront filters on in jsonb with a GIN index, all declared in the service's migration:

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

-- catalog/migrations/1_create_products.up.sql CREATE TABLE products ( sku text PRIMARY KEY, name text NOT NULL, attributes jsonb NOT NULL DEFAULT '{}', raw_payload json NOT NULL ); CREATE INDEX products_attributes_idx ON products USING gin (attributes jsonb_path_ops);
// catalog/catalog.ts import { api } from "encore.dev/api"; import { SQLDatabase } from "encore.dev/storage/sqldb"; const db = new SQLDatabase("catalog", { migrations: "./migrations" }); interface ImportParams { sku: string; name: string; attributes: Record<string, string>; rawPayload: string; // the supplier's body, exactly as received } export const importProduct = api( { expose: false, method: "POST", path: "/products/import" }, async (p: ImportParams): Promise<void> => { await db.exec` INSERT INTO products (sku, name, attributes, raw_payload) VALUES (${p.sku}, ${p.name}, ${JSON.stringify(p.attributes)}::jsonb, ${p.rawPayload}::json) ON CONFLICT (sku) DO UPDATE SET name = EXCLUDED.name, attributes = EXCLUDED.attributes, raw_payload = EXCLUDED.raw_payload `; }, ); interface SearchParams { color: string; } interface SearchResult { skus: string[]; } export const byColor = api( { expose: true, method: "GET", path: "/products/by-color/:color" }, async ({ color }: SearchParams): Promise<SearchResult> => { const skus: string[] = []; const rows = db.query<{ sku: string }>` SELECT sku FROM products WHERE attributes @> ${JSON.stringify({ color })}::jsonb ORDER BY sku LIMIT 100 `; for await (const row of rows) { skus.push(row.sku); } return { skus }; }, );

Template parameters in db.exec and db.query are sent as bind parameters, so the JSON string is never spliced into the SQL text, and the ::jsonb cast happens in Postgres. encore run starts Postgres locally with the GIN index in place, so you can check the plan for the containment query before deploying. The TypeScript databases docs cover the query API, defining APIs explains expose: false for internal endpoints, and the Pub/Sub docs show how a feed importer can publish products for this service to consume.

When an AI coding agent adds a new filter such as size or material, it only needs to extend the attributes object and the query, because the column and index already accept any key, and it can verify the result against the local database in the same change. Production runs the same migration on RDS or Cloud SQL in your AWS or GCP account, provisioned as described in the AWS infrastructure docs.

Best fit: catalog and settings services that keep a few typed columns plus flexible, filterable attributes.

Frequently asked questions

Should I use JSON or JSONB in Postgres?

Use jsonb for almost every column you will query, filter or index, because it supports containment and existence operators and GIN indexes. Use json only when you must keep the exact input text, including key order, whitespace and duplicate keys.

Is JSONB faster than JSON in Postgres?

No, not on writes. jsonb is slightly slower to write because Postgres parses and converts the input, and it can use a little more space for small documents. It is much faster to query, since json has to be reparsed on every access and cannot use a GIN index.

Does JSONB keep key order?

No. jsonb stores keys in its own order, removes insignificant whitespace and keeps only the last value of a duplicate key. If you need the original text byte for byte, store it as json or text.

How do I store JSONB in an Encore service?

Declare a jsonb column in the service's migration and pass JSON.stringify(value) with a ::jsonb cast in the db.exec or db.queryRow template. The same migration runs on the local Postgres that encore run starts and on RDS or Cloud SQL in your account.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders