PostgreSQL JSONB Tutorial: Store, Query and Index JSON the Right Way
On this page
- JSON vs JSONB
- Creating a table with JSONB
- Reading values: -> and ->>
- Filtering rows
- Updating JSONB
- Indexing JSONB
- GIN index for containment and key queries
- Expression index for one hot key
- JSON path queries
- Using JSONB from Node.js
- When to use a column instead
- Validating JSONB with CHECK constraints
- Common mistakes with JSONB
- Frequently asked questions
- Oh hi there 👋It’s nice to meet you.
- Sign up to receive awesome content in your inbox.
PostgreSQL is a relational database, but it also has some of the best JSON support of any database. The JSONB type lets you store flexible, schema-less data, such as product attributes, user settings or webhook payloads, in a normal table, query inside it with SQL, and index it for speed. You get document-style flexibility without giving up transactions, joins and constraints.
This tutorial covers the operators and functions you will actually use, how to index JSONB, how to use it from Node.js, and when a normal column is the better choice. Every SQL example below runs, in order, on a recent PostgreSQL version.
JSON vs JSONB
json |
jsonb |
|
|---|---|---|
| Storage | Exact text, as inserted | Parsed binary format |
| Key order and duplicate keys | Preserved | Not preserved; last duplicate key wins |
| Insert speed | Slightly faster | Slightly slower (parsing) |
| Query speed | Slower: reparsed every time | Fast |
| Indexing (GIN) | Not supported | Supported |
Use jsonb unless you specifically need to keep the original text exactly as it arrived, for example to verify a webhook signature later.
Creating a table with JSONB
CREATE TABLE products (
id serial PRIMARY KEY,
name text NOT NULL,
price numeric(10, 2) NOT NULL,
attributes jsonb NOT NULL DEFAULT '{}'
);
INSERT INTO products (name, price, attributes) VALUES
('Phone X', 24999, '{"brand": "Acme", "ram": 8, "colors": ["black", "blue"], "dims": {"weight": 180}}'),
('Phone Lite', 12999, '{"brand": "Acme", "ram": 4, "colors": ["white"]}'),
('Laptop Pro', 89999, '{"brand": "Zen", "ram": 16, "colors": ["silver"], "ports": ["usb-c", "hdmi"]}');
Keep stable, frequently queried data such as the name and price in normal columns, and use JSONB for the attributes that vary by product. PostgreSQL validates the JSON on insert and rejects anything malformed.
Reading values: -> and ->>
SELECT
name,
attributes -> 'brand' AS brand_json, -- "Acme" (jsonb, with quotes)
attributes ->> 'brand' AS brand, -- Acme (text)
attributes -> 'dims' ->> 'weight' AS weight, -- nested path
attributes #>> '{colors,0}' AS first_color -- path as an array
FROM products;
| Operator | Returns | Example |
|---|---|---|
-> |
jsonb | attributes -> 'dims' |
->> |
text | attributes ->> 'brand' |
#> / #>> |
jsonb / text at a path | attributes #>> '{dims,weight}' |
@> |
boolean: left contains right | attributes @> '{"brand":"Acme"}' |
? |
boolean: key or array element exists | attributes ? 'ports' |
?| / ?& |
any / all of several keys exist | attributes ?| array['ports','dims'] |
Use ->> for comparisons and display, because it returns plain text. Cast it when comparing numbers, otherwise “16” sorts before “8” as text.
Filtering rows
-- containment: products whose attributes include brand Acme
SELECT name FROM products WHERE attributes @> '{"brand": "Acme"}';
-- arrays: products available in blue
SELECT name FROM products WHERE attributes -> 'colors' ? 'blue';
-- key exists: products that list their ports
SELECT name FROM products WHERE attributes ? 'ports';
-- numeric comparison: cast the text value
SELECT name FROM products WHERE (attributes ->> 'ram')::int >= 8 ORDER BY (attributes ->> 'ram')::int DESC;
The containment operator @> is the most important one to learn, because it is what the default GIN index accelerates. It also works with nested objects and arrays: attributes @> '{"colors": ["blue"]}' finds products whose colors include blue.
Updating JSONB
-- set or replace one value (the path must exist up to the last key)
UPDATE products SET attributes = jsonb_set(attributes, '{ram}', '12') WHERE name = 'Phone X';
-- merge in several keys at once with ||
UPDATE products SET attributes = attributes || '{"warranty_years": 2, "refurbished": false}' WHERE name = 'Phone Lite';
-- remove a key with -
UPDATE products SET attributes = attributes - 'refurbished' WHERE name = 'Phone Lite';
-- append to an array
UPDATE products SET attributes = jsonb_set(attributes, '{colors}', (attributes -> 'colors') || '"green"') WHERE name = 'Phone Lite';
These statements change only the parts you name, so two requests updating different keys don’t overwrite each other, unlike reading the whole object into Node.js, changing it and writing it back. Note that || merges only top-level keys; a nested object on the right replaces the whole nested object on the left.
Indexing JSONB
GIN index for containment and key queries
CREATE INDEX products_attributes_gin ON products USING GIN (attributes);
-- a smaller, faster variant that supports @> only
CREATE INDEX products_attributes_path ON products USING GIN (attributes jsonb_path_ops);
A default GIN index speeds up @>, ?, ?| and ?& across all keys. The jsonb_path_ops variant is smaller and often faster, but only supports containment. Choose one based on the operators your queries use.
Expression index for one hot key
GIN indexes don’t help ->> comparisons or sorting. If you constantly filter or sort on one key, index that expression directly:
CREATE INDEX products_brand_idx ON products ((attributes ->> 'brand'));
-- this query can now use the B-tree index
SELECT name FROM products WHERE attributes ->> 'brand' = 'Zen';
Write the query with exactly the same expression as the index, or the planner won’t match them. On tiny tables PostgreSQL may still choose a sequential scan, because reading a few rows directly is cheaper; check with EXPLAIN ANALYZE on realistic data volumes.
JSON path queries
For more complex conditions, PostgreSQL supports the SQL/JSON path language:
-- products with more than 4 GB of RAM, written as a JSON path predicate
SELECT name FROM products WHERE attributes @@ '$.ram > 4';
-- extract every color from every product as rows
SELECT name, jsonb_path_query(attributes, '$.colors[*]') ->> 0 AS color FROM products;
Recent PostgreSQL versions (17 and later) add the SQL-standard JSON_TABLE, JSON_VALUE and JSON_QUERY functions, which turn JSON into rows and columns in a very readable way. If you are on an older version, jsonb_array_elements and jsonb_to_recordset do similar jobs.
Using JSONB from Node.js
With the pg package, JSONB columns arrive as JavaScript objects automatically, and you send objects with JSON.stringify:
import pg from 'pg';
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
const { rows } = await pool.query(
'SELECT name, attributes FROM products WHERE attributes @> $1',
[JSON.stringify({ brand: 'Acme' })]
);
console.log(rows[0].attributes.colors); // ['black', 'blue']
await pool.query(
'UPDATE products SET attributes = attributes || $1 WHERE id = $2',
[JSON.stringify({ onSale: true }), 1]
);
Always pass values as parameters ($1, $2), never by building SQL strings from user input; see how SQL injection works. ORMs such as Prisma, Drizzle and Sequelize also support JSONB columns.
When to use a column instead
JSONB is flexible, but normal columns are faster, smaller and safer for data you rely on. Move a key into its own column when it is present in every row, used in joins or foreign keys, needs constraints such as NOT NULL or UNIQUE, or is filtered and sorted constantly. A good design keeps the core of each row in typed columns and the long tail of optional attributes in JSONB.
Comparing approaches? See MySQL JSON functions for MySQL’s version of these features, and Mongoose schema types for the MongoDB way.
Validating JSONB with CHECK constraints
JSONB accepts any valid JSON, so nothing stops a bug from saving {"ram": "eight"}. CHECK constraints let you enforce the rules that matter while keeping the flexibility:
ALTER TABLE products
ADD CONSTRAINT attributes_is_object CHECK (jsonb_typeof(attributes) = 'object'),
ADD CONSTRAINT brand_present CHECK (attributes ? 'brand'),
ADD CONSTRAINT ram_is_number CHECK (NOT attributes ? 'ram' OR jsonb_typeof(attributes -> 'ram') = 'number');
Now an insert without a brand, or with RAM stored as text, fails immediately with a clear constraint error. Validate in your application too, for friendly error messages, for example with a Zod schema in Express, and let the database act as the final safety net for every code path, including scripts and manual fixes.
Common mistakes with JSONB
- Comparing
->results with text.attributes -> 'brand' = 'Acme'fails, because the left side is JSON. Use->>, or compare with a JSON value using@>. - Forgetting casts.
->>always returns text, so>andORDER BYbehave alphabetically until you cast tointornumeric. - Expecting
||to merge deeply. It merges only top-level keys. Usejsonb_setwith a path to change something nested. - Rewriting whole documents from the application. Read-modify-write cycles lose concurrent changes. Update with
jsonb_set,||and-in SQL instead. - Indexing everything with GIN by default. GIN indexes are larger and slower to update than B-tree indexes. Add them for the query patterns that need them, and measure with
EXPLAIN ANALYZE.
Frequently asked questions
Should I use json or jsonb in PostgreSQL?
Use jsonb in almost all cases. It is faster to query and can be indexed. Use json only when you must keep the exact original text, including key order and whitespace.
Can PostgreSQL replace MongoDB?
For many applications, JSONB gives enough document flexibility while keeping relational features. MongoDB still offers advantages for some workloads, such as built-in horizontal scaling and a document-first developer experience. Choose based on your data and team.
Why isn’t my JSONB query using the GIN index?
The default GIN index supports @>, ?, ?| and ?&, not ->> comparisons. Rewrite the filter with @>, or add an expression index for that key.
Is there a size limit for JSONB values?
A single JSONB value can be very large, but big documents are slow to read and update because the whole value is rewritten. Keep JSONB values reasonably small and split large, independent data into separate rows.




